【问题标题】:How to unstack two columns from groupby()如何从 groupby() 中取消堆叠两列
【发布时间】:2021-02-24 21:26:44
【问题描述】:

我有下面的代码来计算每个销售人员在不同地点销售了多少产品

df = df.groupby(['location','sales person','item']).size().unstack().fillna(0) 
df.to_excel(r'c:\users\Tom\Project\info.xlsx')

我的输出如下,但我需要填充 A 列中的空单元格,这意味着我想在第 3 行看到“东”,在第 5 行看到“西”。有没有办法做到这一点?谢谢

【问题讨论】:

  • 在编写 excel 文件之前尝试df.reset_index(inplace=True)

标签: python-3.x pandas pandas.excelwriter


【解决方案1】:

你可以试试:

df.reset_index().to_excel(r'c:\users\Tom\Project\info.xlsx', index=False)

【讨论】:

    【解决方案2】:

    我想你想要reset_index 方法:

    df.reset_index().to_excel(r'c:\users\Tom\Project\info.xlsx')
    

    我显然没有你的数据,但这里有一个类似的例子:

    df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
    d = df.groupby(['species','petal_length'])['sepal_length'].describe()
    d
    d.reset_index()
    

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2023-01-02
      • 2019-12-30
      • 1970-01-01
      • 2019-01-08
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多