社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python Pandas-如何添加总行来求某些列的和,并取其他列的平均值

wolfblitza • 6 年前 • 2224 次点击  

我有以下代码可以按预期工作

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)

print(Table2)

我可以用以下代码添加总行 Table2.loc['Total'] = Table2.sum(axis = 0) 不过,它也将total应用于“Repeat Rat”和“NewCust Rate”列,但我希望能够取total行中这些行的平均值。我怎样才能修改总行数,使之取平均值。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50619
文章 [ 1 ]  |  最新文章 6 年前
jezrael
Reply   •   1 楼
jezrael    6 年前

使用 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())