从pandas groupby中的每个组中选择前n个元素

时间:2016-05-27 11:46:57

标签: python pandas dataframe

我的数据框大致如下:

>>> data
    price currency    
id                
2    1050       EU
5    1400       EU
4    1750       EU
8    4000       EU
7     630      GBP
1    1000      GBP
9    1400      GBP
3    2000      USD
6    7000      USD 

我需要为每种货币提供包含n最高价产品的新数据框,其中n取决于货币,并在另一个数据框中给出:

>>> select_number
          number_to_select
currency       
GBP         2
EU          2
USD         1

如果我必须选择相同数量的最高价格元素,我可以使用pandas.groupby按货币对数据进行分组,然后使用分组对象的head方法。

但是,head只接受一个数字,而不是数组或某个表达式。

当然,我可以编写一个for循环,但这样做我们会非常尴尬和低效。

如何以良好的方式做到这一点?

3 个答案:

答案 0 :(得分:9)

您可以使用:

data = pd.DataFrame({'id': {0: 2, 1: 5, 2: 4, 3: 8, 4: 7, 5: 1, 6: 9, 7: 3, 8: 6}, 'price': {0: 1050, 1: 1400, 2: 1750, 3: 4000, 4: 630, 5: 1000, 6: 1400, 7: 2000, 8: 7000}, 'currency': {0: 'EU', 1: 'EU', 2: 'EU', 3: 'EU', 4: 'GBP', 5: 'GBP', 6: 'GBP', 7: 'USD', 8: 'USD'}})
select_number = pd.DataFrame({'number_to_select': {'USD': 1, 'GBP': 2, 'EU': 2}})
print (data)
  currency  id  price
0       EU   2   1050
1       EU   5   1400
2       EU   4   1750
3       EU   8   4000
4      GBP   7    630
5      GBP   1   1000
6      GBP   9   1400
7      USD   3   2000
8      USD   6   7000

print (select_number)
     number_to_select
EU                  2
GBP                 2
USD                 1

dict映射的解决方案:

d = select_number.to_dict()
d1 = d['number_to_select']
print (d1)
{'USD': 1, 'EU': 2, 'GBP': 2}

print (data.groupby('currency').apply(lambda dfg: dfg.nlargest(d1[dfg.name],'price'))
           .reset_index(drop=True))

  currency  id  price
0       EU   8   4000
1       EU   4   1750
2      GBP   9   1400
3      GBP   1   1000
4      USD   6   7000

溶液2:

print (data.groupby('currency')
           .apply(lambda dfg: (dfg.nlargest(select_number
                                   .loc[dfg.name, 'number_to_select'], 'price')))
           .reset_index(drop=True))

   id  price currency
0   8   4000       EU
1   4   1750       EU
2   9   1400      GBP
3   1   1000      GBP
4   6   7000      USD

说明:

我认为调试是f的最佳使用函数print

def f(dfg):
    #dfg is DataFrame 
    print (dfg)
    #name of group
    print (dfg.name)
    #select value from select_number  
    print (select_number.loc[dfg.name, 'number_to_select']) 
    #return top rows per groups 
    print (dfg.nlargest(select_number.loc[dfg.name, 'number_to_select'], 'price'))
    return (dfg.nlargest(select_number.loc[dfg.name, 'number_to_select'], 'price'))

print (data.groupby('currency').apply(f))
  currency  id  price
0       EU   2   1050
1       EU   5   1400
2       EU   4   1750
3       EU   8   4000
  currency  id  price
0       EU   2   1050
1       EU   5   1400
2       EU   4   1750
3       EU   8   4000
EU
2
  currency  id  price
3       EU   8   4000
2       EU   4   1750
  currency  id  price
4      GBP   7    630
5      GBP   1   1000
6      GBP   9   1400
GBP
2
  currency  id  price
6      GBP   9   1400
5      GBP   1   1000
  currency  id  price
7      USD   3   2000
8      USD   6   7000
USD
1
  currency  id  price
8      USD   6   7000

           currency  id  price
currency                      
EU       3       EU   8   4000
         2       EU   4   1750
GBP      6      GBP   9   1400
         5      GBP   1   1000
USD      8      USD   6   7000

答案 1 :(得分:3)

这是一个解决方案:

select_number = select_number['number_to_select']  # easier to select from series

df.groupby('currency').apply(
    lambda dfg: dfg.nlargest(select_number[dfg.name], columns='price')
)

修改 - 我从jezrael's answer得到了答案:我将dfg.currency.iloc[0]替换为dfg.name

第二次修改 - 正如评论中所指出的,select_number是一个数据框,因此我首先将其转换为系列。

MaxU和jezrael,感谢您的评论!

答案 2 :(得分:1)

你可以这样做:

df['rn'] = (df.sort_values(['price'], ascending=False)
              .groupby('currency').cumcount() + 1
)

qry = (select_number
       .reset_index()
       .astype(str)
       .apply(lambda x: '((currency=="{0[0]}") & (rn<={0[1]}))'.format(x), axis=1)
       .str.cat(sep=' | ')
)

print(df.query(qry))

输出

In [147]: df.query(qry)
Out[147]:
    price currency  rn
id
4    1750       EU   2
8    4000       EU   1
1    1000      GBP   2
9    1400      GBP   1
6    7000      USD   1

说明:

rn - 是一个帮助列 - 每个分区/组的row_number,按price降序排列(在该组内)

qry - 是动态生成的查询

In [149]: qry
Out[149]: '((currency=="EU") & (rn<=2)) | ((currency=="GBP") & (rn<=2)) | ((currency=="USD") & (rn<=1))'