我正在使用这个数据框
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
总计是每个来源当年所有水果的总和。
种子是每个来源每年含有种子的水果的总和。
我试过了
追加新的空行:Insert a new row after every nth row & Insert row at any position
但没有得到预期的结果。
获得所需输出的最佳方法是什么?
最佳答案
尝试:
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])
关于python - 根据其组重新定义 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67468917/