[英]Python Pandas - how to add a total row to sum certain columns and take the average for others
I have the following code that is working as intended我有以下代码按预期工作
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())
Instead of calculating the means for "Repeat Rate" and "NewCust Rate" as the code is doing now, how can I formulas so that the total rows for those columsn are using the following formulas instead:不是像代码现在所做的那样计算“重复率”和“新客户率”的平均值,我如何制定公式,以便这些列的总行数使用以下公式:
Repeat Rate = Table['Existing Customer']/Table2['TotalCusts'] NewCust Rate = Table['New Customer']/Table2['TotalCusts']重复率 = Table['现有客户']/Table2['TotalCusts'] NewCust Rate = Table['New Customer']/Table2['TotalCusts']
Use Index.difference
for all columns without specifying in list for sum
and columns in list for mean
with Series.append
for join together:对所有列使用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.