Skip to main content
 首页 » 编程设计

python之在两列上使用 groupby() 时获取每组的最大值 ~Python

2024年10月01日6TianFang

使用类似格式的 csv(csv 总数约为 500 x 600,000),因此缺少列:

       Sales  market_id  product_id 
 
0         38   10001516     1132679 
1         49   10001516     1138767 
2          6   10001516     1132679 
     ...        ...         ... 
9969  245732    1002123     1383020 
9970  247093    1006821     1383020 

等 并像这样阅读它: df0=pd.read_csv('all_final_decomps2_small.csv', low_memory=False, encoding='iso8859_15')

我正在尝试为每个 market_id 查找具有最大销售额的 product_id。为此,我需要对销售额求和,因为相同的 product_id 和 market_id 可以出现在多行中。

我试过这个,它产生每个市场内的产品总和:

df_sales=df0[['Sales','market_id','product_id']]  
df_sales.groupby(['market_id', 'product_id'])['Sales'].sum() 

如此(缩短):

market_id  product_id 
1006174    1132679             2789 
           1382460             4586 
           1382691               49 
           1383020        269138089 
1006638    1132679          5143156 
           1382460           387250 
           1383020        204456809 
10002899   1132679              630 
           1382464              220 

使用:

df_sales.groupby(['market_id', 'product_id'])['Sales'].sum().max() 

返回总和的最大值,没有别的,所以在这个例子中它会返回 269138089。我想返回这样的东西:

market_id  product_id      max_sales 
1006174    1383020        269138089 
1006638    1383020        204456809 
10002899   1132679              630 

我已经尝试了很多不同的东西,但我似乎无法为这个例子做任何事情,所以我很感激任何帮助(如果之前有人问过我,我很抱歉)。

我正在使用: Python 3.6.1::Anaconda 4.4.0(64 位)

请您参考如下方法:

在 groupby 中使用 idxmax

设置

import pandas as pd 
from io import StringIO 
 
txt = """market_id  product_id         Sales 
1006174    1132679             2789 
1006174    1382460             4586 
1006174    1382691               49 
1006174    1383020        269138089 
1006638    1132679          5143156 
1006638    1382460           387250 
1006638    1383020        204456809 
10002899   1132679              630 
10002899   1382464              220""" 
 
 
sales = pd.read_csv(StringIO(txt), delim_whitespace=True, index_col=[0, 1], squeeze=True) 

解决方案

sales.loc[sales.groupby(level=0).idxmax()] 
 
market_id  product_id 
1006174    1383020       269138089 
1006638    1383020       204456809 
10002899   1132679             630 
Name: Sales, dtype: int64 

或者

sales.loc[sales.groupby(level=0).idxmax()].reset_index(name='max_sales') 
 
   market_id  product_id  max_sales 
0    1006174     1383020  269138089 
1    1006638     1383020  204456809 
2   10002899     1132679        630