Pandas 为数据帧中的每个子组添加总行
我有一个数据帧,df:Pandas 为数据帧中的每个子组添加总行,pandas,group-by,sum,row,Pandas,Group By,Sum,Row,我有一个数据帧,df: BRAND ART_TYPE YEAR_MONTH metrics Value aaa xyz 201510 a 4500 aaa xyz 201510 b 8500 bbc abc 201510 c 3500 bbc abc 201510 d 10000 xxx def 201510 e 15
BRAND ART_TYPE YEAR_MONTH metrics Value
aaa xyz 201510 a 4500
aaa xyz 201510 b 8500
bbc abc 201510 c 3500
bbc abc 201510 d 10000
xxx def 201510 e 15000
我想为每组([‘品牌’、‘艺术类型’、‘年\月’)添加一行)
因此,结果应该是:
BRAND ART_TYPE YEAR_MONTH metrics Value
aaa xyz 201510 a 4500
aaa xyz 201510 b 8500
aaa xyz 201510 tot 13000
bbc abc 201510 c 3500
bbc abc 201510 d 10000
bbc abc 201510 tot 13500
xxx def 201510 e 15000
xxx def 201510 tot 15000
如何做到这一点?我们有什么功能吗?我尝试了apply和groupby函数,但没有成功。如果需要更多信息,请告诉我
我尝试的代码添加了一列:
df['total'] = df.groupby(['BRAND','ART_TYPE','YEAR_MONTH']).apply(calctot)
def calctot(df):
return(sum(df['Value']))
这给出了一个错误,即使它工作,这将添加一列 我必须根据建议的输出更改输入数据帧。
我改进了函数
calctot
——删除列,然后追加求和行。
列level_3
是从旧索引创建的,我将其删除。应用函数groupby
后,metrics
列中的新值是NaN
,因此我用值tot
填充它们
# BRAND ART_TYPE YEAR_MONTH metrics Value
#0 aaa xyz 201510 a 4500
#1 aaa xyz 201510 b 8500
#2 bbc abc 201510 c 3500
#3 bbc abc 201510 d 10000
#4 xxx def 201510 e 15000
def calctot(df):
#delete columns
df = df.drop(['BRAND', 'ART_TYPE', 'YEAR_MONTH'], axis=1)
#append sum row, ignoring non-numeric column metrics
return df.append(df.sum(numeric_only=True), ignore_index=True)
#groupby and reset index
df = df.groupby(['BRAND','ART_TYPE','YEAR_MONTH']).apply(calctot).reset_index()
#delete old index column
df = df.drop(['level_3'], axis=1)
#fill NaN to value tot
df['metrics'] = df['metrics'].fillna('tot')
print df
# BRAND ART_TYPE YEAR_MONTH metrics Value
#0 aaa xyz 201510 a 4500
#1 aaa xyz 201510 b 8500
#2 aaa xyz 201510 tot 13000
#3 bbc abc 201510 c 3500
#4 bbc abc 201510 d 10000
#5 bbc abc 201510 tot 13500
#6 xxx def 201510 e 15000
#7 xxx def 201510 tot 15000