【问题标题】:Reshaping pandas dataframe with unstack()使用 unstack() 重塑 pandas 数据框
【发布时间】: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。尽管我尝试过,但我仍然无法重新排列它以获得我想要的输出采用hereherehere 发布的解决方案。有什么建议吗?

【问题讨论】:

  • 想要的输出是什么?
  • 我后面的输出是最后一个帖子,但是有不同的列,必须有第一列Section,第二列Seller,第三列Store,第四列2018,第五列2018..

标签: python python-3.x pandas


【解决方案1】:

如果我理解正确,您似乎只是错过了一个 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()

【讨论】:

  • 有什么方法可以得到某种连接列名的 2017 年和 2018 年,以便将它们命名为“Total_pieces: 2017”和“Total_pieces: 2018”?
  • 是的。不是很优雅,但在上面的解决方案中,您可以将df.columns.droplevel(0).rename('') 替换为df.columns.get_level_values(0) + ': ' + df.columns.get_level_values(1)
  • 谢谢!这也适用于 pd.pivot_table()。
猜你喜欢
  • 1970-01-01
  • 2017-11-05
  • 2023-04-08
  • 2023-02-04
  • 2018-09-24
  • 2012-12-10
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多