繁体   English   中英

Python Pandas - 如何添加总行以对某些列求和并为其他列求平均值

[英]Python Pandas - how to add a total row to sum certain columns and take the average for others

我有以下代码按预期工作

df['FPYear'] = df['First_Purchase_Date'].dt.year
# Table2 = df.loc[df.Date.between('2018-11-22','2018-11-30')].groupby(df['FPYear'])[['New Customer', 'Existing Customer', 'revenue']].sum() #with date filters for table
Table2 = df.loc[df.Date.between('2018-11-22','2018-11-30') & (df['Region'] == 'Canada')].groupby(df['FPYear'])[['New Customer', 'Existing Customer', 'revenue']].sum() #with date filters for table
Table2['TotalCusts'] = Table2['New Customer'] + Table2['Existing Customer']
Table2['Cohort Size'] = Table['New Customer']

Table2['Repeat Rate'] = Table2['Existing Customer']/Table2['TotalCusts']
Table2['NewCust Rate'] = Table2['New Customer']/Table2['TotalCusts']
Table2['PCT of Total Yr'] = Table2['TotalCusts']/Table['New Customer']
Table2.loc['Total'] = Table2.sum(axis = 0) this code totals all columns.  #the below calcs totals for some and average for others

cols = ["Repeat Rate", "NewCust Rate"]
diff_cols = Table2.columns.difference(cols)
Table2.loc['Total'] = Table2[diff_cols].sum().append(Table2[cols].mean())

不是像代码现在所做的那样计算“重复率”和“新客户率”的平均值,我如何制定公式,以便这些列的总行数使用以下公式:

重复率 = Table['现有客户']/Table2['TotalCusts'] NewCust Rate = Table['New Customer']/Table2['TotalCusts']

对所有列使用Index.difference而不在列表中指定sum ,将列表中的列指定为mean使用Series.append连接在一起:

cols = ["Repeat Rate", "NewCust Rate"]
diff_cols = Table2.columns.difference(cols)
Table2.loc['Total'] = Table2[diff_cols].sum().append(Table2[cols].mean())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM