如何按列分组并获得该列中每个类别的前 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/