python pandas - 运行idxmax / argmax后得到一个列值

问题描述 投票:1回答:3

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

通过运行,我可以获得收入最高的类别的实际总收入:

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

但是,如何获得最大收入所属的category_id?即total_sales数量最多的category_id

python pandas pandas-groupby
3个回答
1
投票

通过使用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

2
投票

使用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调用的时间可以忽略不计,因此这应该是非常高效的。


1
投票

我认为你需要idxmax,但对于返回索引添加[]

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
© www.soinside.com 2019 - 2024. All rights reserved.