【问题标题】:Getting the minimum and maximum after using group by使用 group by 后获取最小值和最大值
【发布时间】:2020-06-24 23:56:45
【问题描述】:

我的数据框包含名为:CityProduct lineQuantity 和其他几个对我的问题不重要的列。 p>

我想找出每个城市中哪些产品线具有最小和最大平均数量。

我使用了 groupby 函数。这是我的代码:

import pandas as pd
dataset = pd.read_csv('supermarket_sales.csv')
stats_product_line_by_cities = dataset.groupby(['City', 'Product line'])['Quantity'].mean()

输出如下所示

City       Product line          
Mandalay   Electronic accessories    5.745455
           Fashion accessories       4.790323
           Food and beverages        5.400000
           Health and beauty         6.037736
           Home and lifestyle        5.900000
           Sports and travel         5.193548
Naypyitaw  Electronic accessories    6.054545
           Fashion accessories       5.261538
           Food and beverages        5.590909
           Health and beauty         5.326923
           Home and lifestyle        5.444444
           Sports and travel         5.888889
Yangon     Electronic accessories    5.366667
           Fashion accessories       5.156863
           Food and beverages        5.396552
           Health and beauty         5.468085
           Home and lifestyle        5.707692
           Sports and travel         5.644068
Name: Quantity, dtype: float64

这是一种幸运的输出。现在我只想拉出每个城市的最小值和最大值。我该怎么做?

【问题讨论】:

标签: python pandas pandas-groupby


【解决方案1】:

让我们做sort_valuesgroupby head + tail

g=stats_product_line_by_cities.sort_values().groupby(level=0)
out=pd.concat([g.head(1),g.tail(1)])

【讨论】:

  • 谢谢。有效。你能解释一下 groupby(level=0) 的工作原理吗?我试图在文档中找到它,但是没有结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多