类似于 Excel 的 Pandas 小计

问题描述

我有以下数据框 df

     A   B      C
0    21  Blue   100 
1    33  Yellow 100 
2    17  White  250 
3    A2  Grey   40
4    65  Green  500 
5    33  Red    80 
6    17  Purple -50
7    A2  Orange 600

B 列基本上是不相关的信息 IRT 代码本身,但仍需要包含在输出中。 我已经按列 A 对数据框进行了排序,并解决了 col A 包含 int 和 str 的问题:

df['A'] = df['A'].astype(str)
df_sorted = df.sort_values(by=['A'])

所以现在 df_sorted 看起来像这样:

     A   B      C
2    17  White  250
6    17  Purple -50
0    21  Blue   100
1    33  Yellow 100
5    33  Red    80
4    65  Green  500
3    A2  Grey   40
7    A2  Orange 600

我的问题是:如何通过总结类似于 Excel 的小计函数的 col C 来为 col A 中的每个更改进行小计? 数据帧的最终输出应如下所示:

     A        B      C
2    17       White  250
6    17       Purple -50
     Subtotal        200  
0    21       Blue   100
     Subtotal        100
1    33       Yellow 100
5    33       Red    80
     Subtotal        180
4    65       Green  500
     Subtotal        500
3    A2       Grey   40
7    A2       Orange 600
     Subtotal        640

解决方法

您可以concat您的原始 df 和 groupby 小计。

df1 =  pd.concat([df,df.groupby(['A'],as_index=False)['C'].sum()]).sort_values('A')

df1.loc[df1['B'].isnull(),'A'] = 'Subtotal'

print(df1.fillna(''))

          A       B    C
2        17   White  250
6        17  Purple  -50
0  Subtotal          200
0        21    Blue  100
1  Subtotal          100
1        33  Yellow  100
5        33     Red   80
2  Subtotal          180
4        65   Green  500
3  Subtotal          500
3        A2    Grey   40
7        A2  Orange  600
4  Subtotal          640

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...