【发布时间】:2018-03-21 20:58:25
【问题描述】:
我正在尝试重塑 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'])
因此,我将其重塑为:
df = df.set_index(['Section', 'Seller', 'Store', 'Selected_period']).unstack(level = -1)
df = df.fillna(0)
df.columns = df.columns.droplevel(0)
输出:
但是,我希望在最终数据框中仅包含以下列:Section, Seller, Store, 2017, 2018。尽管我尝试过,但我仍然无法重新排列它以获得我想要的输出采用here 和here 和here 发布的解决方案。有什么建议吗?
【问题讨论】:
-
你做想要的输出是什么?
-
我后面的输出是最后一个帖子,但是有不同的列,必须有第一列Section,第二列Seller,第三列Store,第四列2018,第五列2018..
标签: python python-3.x pandas