python pandas - 在 运行 idxmax / argmax 之后获取列值

python pandas - getting a column value after running idxmax / argmax

我正在尝试通过一些数据找出哪一类产品的收入最高。

我可以通过运行得到收入最高的品类的实际总收入:

max_revenue_by_cat = summer_transactions.groupby('item_category_id')['total_sales'].sum().max()

但是我如何才能获得最大收入所属的 category_id?即 total_sales

数量最多的 category_id

我认为您需要 idxmax,但对于 return 索引添加 []:

summer_transactions = pd.DataFrame({'A':list('abcdef'),
                                    'total_sales':[5,3,6,9,2,4],
                                    'item_category_id':list('aaabbb')})


df = summer_transactions.groupby('item_category_id')['total_sales'].sum()

s = df.loc[[df.idxmax()]]
print (s)
item_category_id
b    15
Name: total_sales, dtype: int64


df = df.loc[[df.idxmax()]].reset_index(name='col')
print (df)
  item_category_id  col
0                b   15

使用set_index + sum(level=0) + sort_values + iloc 索引第一项。

df

   item_category_id  total_sales
0                 1          100
1                 1           10
2                 0          200
3                 2           20
4                 1          300
5                 0          100
6                 1           30
7                 2          400

r = df.set_index('item_category_id')\
      .total_sales.sum(level=0)\
      .sort_values(ascending=False)\
      .iloc[[0]]

item_category_id
1    440
Name: total_sales, dtype: int64

如果你想把它作为一个迷你数据框,在结果上调用 reset_index -

r.reset_index()

   item_category_id  total_sales
0                 1          440

详情

df.set_index('item_category_id').total_sales.sum(level=0)

item_category_id
1    440
0    300
2    420
Name: total_sales, dtype: int64

这里,总和最大的类别是1。通常,对于少量组,sort_values 调用花费的时间可以忽略不计,因此这应该是非常高效的。

通过使用 coldspeed 的数据:-)

(df.groupby('item_category_id').total_sales.sum()).loc[lambda x : x==x.max()]


Out[11]: 
item_category_id
1    440
Name: total_sales, dtype: int64