繁体   English   中英

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

使用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 ,请对结果调用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调用花费的时间可以忽略不计,因此这应该表现得很好。

我认为您需要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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM