python - 为每个类别python选择前10条记录

标签 python pandas dataframe

如何按列分组并获得该列中每个类别的前 10 条记录?

我要分组的列有 3 个类别“高”、“中”和“低”。

我有另一列包含我用来对数据进行排名的数字数据。

这是我的数据框的头部:

country   designation     points    province               title             year    price   price_category
Italy     Vulkà Bianco     98        Sicily     Nicosia 2013 Vulkà Bianco    2013     65     high

我的代码返回数字列中的前 2 列,但我丢失了所有其他列。有没有办法在不丢失其他列的情况下做到这一点?

df.groupby('price_category')['points'].nlargest(2)

这是我丢失所有其他列的输出:

category_column        
high        36528     100
            42197     100
low         5011       95
            15196      95
med         114981     97
            9901       96

我需要这个 ^ 但不会丢失我的其他专栏。

最佳答案

你需要:

df = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10,11,12], 
                   'level':['low','high','low','medium','medium','high','low','high','medium','high','medium','low'],
                   'values':[23,43,56,12,34,32,18,109,345,21,15,45]})

# use nlargest(10) for your problem. 
print(df.groupby('level')['values'].nlargest(2))

输出:

level                                                                                                                                         
high    7     109                                                                                                                             
        1      43                                                                                                                             
low     2      56                                                                                                                             
        11     45                                                                                                                             
medium  8     345                                                                                                                             
        4      34   

关于python - 为每个类别python选择前10条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54954982/

相关文章:

python - Pandas 累积/元素方式

python - 从 Excel 多表文件 : List comprehension between columns 解析

python - 如何在 pandas 中找到两个相等的最小值?

python - 每个唯一值采样一条记录( Pandas , python )

python - 计算向量范数相对于python中向量的梯度

python - 从文本文件读取字典将整数键转换为字符串 : Python

python - 为什么groupby这么快?

python - 将属性(不是函数)传递给 python `pandas.DataFrame.style`

python - 使 pyinstaller --onefile install 可移植

python - 在函数内修改字典