如何从groupby()绘图?

2024-04-20 06:11:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个DataFrame,我正在使用groupby()函数分析它。我想画出结果。你知道吗

这是一段代码:

df = df[(df['Type'] == 'u')]
df['Date'] =  pd.to_datetime(df['Date'], format='%d-%m-%Y')
df['Month'] = df['Date'].dt.month 
mean_prices = df.groupby((['Suburb','Rooms', 'Month']))['Price'].agg(np.mean).round()
mean_prices

结果如下:

Suburb              Rooms  Month
    Abbotsford          1      5         432250.0
                               7         470000.0
                               8         441500.0
                               10        300000.0
                               11        490000.0
                               12        481000.0
                        2      5         970000.0
                               6         500000.0
                               10        542000.0
                               11        725000.0
                               12        760000.0
    Aberfeldie          1      12        380000.0
                        2      5         456000.0
                               11        373000.0
                        3      9         726000.0
                               12        845000.0
    Airport West        2      7         468250.0

我想对agg()np.maxnp.min做一个方框图,显示每个郊区的最大值、最小值和平均值。怎么做?你知道吗


Tags: 函数代码dataframedfdatetypenpmean
1条回答
网友
1楼 · 发布于 2024-04-20 06:11:22

您可以使用aggregate应用如下多个函数:

mean_prices = df.groupby((['Suburb','Rooms', 'Month']))['Price'].aggregate({'Mean': np.mean, 'Min': np.min, 'Max': np.max}).round().reset_index()
mean_prices.head()

你会得到:

    Suburb    Rooms Month   Mean    Min         Max
0   Abbotsford  1   5   432250.0    423500.0    441000.0
1   Abbotsford  1   7   470000.0    470000.0    470000.0
2   Abbotsford  1   8   441500.0    426000.0    457000.0
3   Abbotsford  1   10  300000.0    300000.0    300000.0
4   Abbotsford  1   11  490000.0    480000.0    500000.0

相关问题 更多 >