python - 使用 unstack() reshape pandas 数据框

标签 python python-3.x pandas

我正在尝试 reshape pandas DataFrame,以便其中一列将被拆分为“更广泛”。一旦我继续使用 unstack() ,就会出现新的列级别,但我似乎无法按照我想要的方式重新排列标题。

首先,我有以下 df:

from pandas import *

fList = [['Packs', 'Brablik', 'Holesovice', '2017', 100],
         ['Decorations', 'Drapp-design', 'Holesovice', '2017', 150],
         ['Decorations', 'Klapetkovi', 'Holesovice', '2017', 200],
         ['Decorations', 'Lezecké dárky', 'Fler', '2017', 100],
         ['Decorations', 'PP', 'Other', '2017', 350],
         ['Decorations', 'Pavlimila', 'Akce', '2017', 20],
         ['Decorations', 'Pavlimila', 'Holesovice', '2017', 50],
         ['Decorations', 'Wiccare', 'Holesovice', '2017', 70],
         ['Toys', 'Klára Vágnerová', 'Holesovice', '2017', 100],
         ['Toys', 'Lucie Polonyiová', 'Holesovice', '2017', 80],
         ['Dresses', 'PP', 'Other', '2018', 200]]

df = DataFrame(fList, columns = ['Section', 'Seller', 'Store', 'Selected_period', 'Total_pieces'])

这会产生: enter image description here

因此我将其 reshape 为:

df = df.set_index(['Section', 'Seller', 'Store', 'Selected_period']).unstack(level = -1)
df = df.fillna(0)
df.columns = df.columns.droplevel(0)

输出:

enter image description here

但是,我想在最终的数据框中只包含以下列:部分、卖家、商店、2017、2018。尽管我尝试过,但我仍然无法重新排列它,以便获得我想要的输出采用发布的解决方案hereherehere 。有什么建议吗?

最佳答案

如果我理解正确,您似乎只是错过了 reset_index() 调用。试试这个:

df = df.set_index(['Section', 'Seller', 'Store', 'Selected_period']).unstack(level = -1).fillna(0)
df.columns = df.columns.droplevel(0).rename('')
df = df.reset_index()

enter image description here

关于python - 使用 unstack() reshape pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49404001/

相关文章:

python - 如何最有效地将方形numpy矩阵 reshape 为对角线结构的 "diamond"

python-3.x - 赋值操作Python

python - 通过 tox 运行 Sphinx

python - 在 Python 中使用并从 Apk 导入 .SO native 库

python - 为什么 print 不是 python 中的函数?

python - 将 NumPy 数组的指定元素转换为新值

Python:用底层分布替换值

python - Pandas :将数据框插入其他数据框而不保留索引

python - Pandas :在给定条件下填充nans

python requests 模块 - 将键设置为 null