在保留所有列的pandas中获取每个类别的前n个值

Alb*_*nto 6 python pandas

在进行了一些转换之后dataframe,我得到了以下内容,在这种情况下如何通过列获取前n条记录short_name并使用其他作为指标frequency.我读过这篇文章,但两个解决方案的问题是他们摆脱了列product_name,他们只保留了分组列,我需要保留它们.

short_name          product_id    frequency
Yoghurt y cereales  975009684     32
Yoghurt y cereales  975009685     21
Yoghurt y cereales  975009700     16
Yoghurt y Cereales  21097         16
Yoghurt Bebible     21329         68
Yoghurt Bebible     21328         67
Yoghurt Bebible     21500         31
Run Code Online (Sandbox Code Playgroud)

Max*_*axU 6

我会尝试使用nlargest方法:

In [5]: df.groupby('short_name', as_index=False).apply(lambda x: x.nlargest(2, 'frequency'))
Out[5]:
             short_name  product_id  frequency
0 4     Yoghurt Bebible       21329         68
  5     Yoghurt Bebible       21328         67
1 3  Yoghurt y Cereales       21097         16
2 0  Yoghurt y cereales   975009684         32
  1  Yoghurt y cereales   975009685         21
Run Code Online (Sandbox Code Playgroud)


Sco*_*ton 5

你可以试试这个:

df.groupby('short_name', as_index=False).apply(lambda x: x.sort_values(by='frequency',ascending=False).head(2)).reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

输出:

           short_name  product_id  frequency
0     Yoghurt Bebible       21329         68
1     Yoghurt Bebible       21328         67
2  Yoghurt y Cereales       21097         16
3  Yoghurt y cereales   975009684         32
4  Yoghurt y cereales   975009685         21
Run Code Online (Sandbox Code Playgroud)


EFT*_*EFT 5

您可以先对数据帧进行排序,然后使用groupby:

df.sort_values('frequency', ascending=False).groupby('short_name').head(2)
Out[28]: 
           short_name  product_id  frequency
4     Yoghurt Bebible       21329         68
5     Yoghurt Bebible       21328         67
0  Yoghurt y cereales   975009684         32
1  Yoghurt y cereales   975009685         21
3  Yoghurt y Cereales       21097         16
Run Code Online (Sandbox Code Playgroud)