gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:24:49 25 4
gpt4 key购买 nike

经过一些转换后,我得到了以下 dataframe,在这种情况下,我如何继续按列获取前 n 条记录 short_name 并使用其他作为指标 频率。我读了这个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

最佳答案

我会尝试使用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

关于python - 在保留所有列的 Pandas 中获取每个类别的前 n 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com