【问题标题】:Redefining a pandas dataframe based on its group根据组重新定义熊猫数据框
【发布时间】:2021-07-31 18:24:45
【问题描述】:

我正在使用这个数据框

  source   fruit  2019  2020  2021
0      a   apple     3     1     1
1      a  banana     4     3     5
2      a  orange     2     2     2
3      b   apple     3     4     5
4      b  banana     4     5     2
5      b  orange     1     6     4

我想像这样细化它

 source   fruit  2019  2020  2021
0      a   total     9     6     8
1      a   seeds     5     3     3
2      a  banana     4     3     5
3      b   total     8    15    11
4      b   seeds     4    10     9
5      b  banana     4     5     2

total 是每个来源当年所有水果的总和。
种子是每个来源每年含有种子的果实的总和。

我试过了
追加新的空行:Insert a new row after every nth row & Insert row at any position
但没有得到预期的结果。

获得所需输出的最佳方法是什么?

【问题讨论】:

    标签: python pandas dataframe aggregate


    【解决方案1】:

    试一试:

    df1 = df.groupby('source', as_index=False).sum().assign(fruit = 'total')
    seeds = ['orange','apple']
    df2 = df.loc[df['fruit'].isin(seeds)].groupby('source', as_index=False).sum().assign(fruit = 'seeds')
    final_df = pd.concat([df.loc[~df['fruit'].isin(seeds)], df1,df2])
    

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 2019-03-20
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多