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

在进行了一些转换之后,我获得了以下数据帧,如何通过本例short_name中的列并使用其他作为指示符频率来获取前n个记录.我读了这个post,但两个解决方案的问题是他们摆脱了列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

解决方法:

您可以先对数据帧进行排序,然后使用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

posted @   锐洋智能  阅读(188)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过
点击右上角即可分享
微信分享提示