【问题标题】:Calulate the groupby (several columns) average in pandas [duplicate]计算熊猫中的groupby(几列)平均值[重复]
【发布时间】:2020-04-18 12:13:11
【问题描述】:

我有一个如下所示的数据框。

Unit_ID    Price           Sector    Contract_Date    Rooms
1          20              SE1       16-10-2015       2
9          40              SE1       20-10-2015       2
2          40              SE1       16-10-2016       3
2          30              SE1       16-10-2015       3
3          20              SE1       16-10-2015       3
3          10              SE1       16-10-2016       3
4          60              SE1       16-10-2016       2
5          40              SE2       16-10-2015       2
8          80              SE1       20-10-2015       2
6          80              SE2       16-10-2016       3
6          60              SE2       16-10-2015       3
7          40              SE2       16-10-2015       3
7          20              SE2       16-10-2015       3
8          120             SE2       16-10-2016       2

从上面我想在熊猫中准备一个如下所示的数据框。

预期输出:

Sector       Rooms    Year         Average_Price
SE1          2        2015         30
SE1          2        2016         60
SE1          3        2015         25
SE1          3        2016         25
SE2          2        2015         60
SE2          2        2016         120
SE2          3        2015         50
SE2          3        2016         50

我想我应该使用 pandas groupby

我尝试了以下代码

df['Year'] = df.Contract_Date.dt.year
df1 = df.groupby(['Sector', 'Year', 'Rooms']).Price.mean()

【问题讨论】:

  • 那不行吗?您的 Date_Created 实际上是日期类型吗?你得到什么错误/结果?
  • @JonClements 我希望它采用正确的表格格式,而不是系列。
  • 我认为你的代码工作正常,除了你错过了索引 8,--> 80 SE1 20-10-2015 2 例如在你的手动计算中,你只取了前两行 room 2 @987654327 @和部门SE1
  • 也许你需要像这样添加reset_index()df.groupby(['Sector', 'Year', 'Rooms']).Price.mean().reset_index()
  • 或:df.groupby(['Sector', 'Year', 'Rooms'],as_index=False).Price.mean()

标签: pandas pandas-groupby


【解决方案1】:

用途:

( df.groupby(['Sector','Rooms',df['Contract_Date'].dt.year.rename('Year')])
    .Price
    .mean()
    .rename('Average_Price')
    .reset_index() )

  Sector  Rooms  Year  Average_Price
0    SE1      2  2015      46.666667
1    SE1      2  2016      60.000000
2    SE1      3  2015      25.000000
3    SE1      3  2016      25.000000
4    SE2      2  2015      40.000000
5    SE2      2  2016     120.000000
6    SE2      3  2015      40.000000
7    SE2      3  2016      80.000000

或使用groupby.agg:

( df.groupby(['Sector','Rooms',df['Contract_Date'].dt.year.rename('Year')])
    .Price
    .agg(Average_Price = 'mean')
    .reset_index() )

【讨论】:

  • 正要建议.agg 方法...
  • (虽然不是.Price.agg(...) - 我可能很想直接跳到agg,例如:.agg(Average_Price=('Price', 'mean')) 而不是
  • 变种很多,可见一斑。
猜你喜欢
  • 2019-12-23
  • 2018-04-29
  • 2020-03-03
  • 1970-01-01
  • 2021-02-27
  • 2019-07-27
  • 1970-01-01
  • 2020-04-09
相关资源
最近更新 更多