如何选择pandas中每组的前3行?

时间:2017-09-01 03:20:37

标签: python pandas

我得到像这样的pandas数据框:

    id   prob
0    1   0.5   
1    1   0.6
2    1   0.4
3    1   0.2
4    2   0.3
6    2   0.5
...

我想按'id'对其进行分组,按降序排序并获得每组的前3个概率。请注意,某些组包含小于3的行。 最后,我想获得一个像以下的2D数组:

[[1, 0.6, 0.5, 0.4], [2, [0.5, 0.3]]...]

我怎么能用熊猫做到这一点? 谢谢!

4 个答案:

答案 0 :(得分:3)

使用sort_valuesgroupbyhead

df.sort_values(by=['id','prob'], ascending=[True,False]).groupby('id').head(3).values

输出:

array([[ 1. ,  0.6],
       [ 1. ,  0.5],
       [ 1. ,  0.4],
       [ 2. ,  0.5],
       [ 2. ,  0.3]])

关注@COLDSPEED主持人:

df.sort_values(by=['id','prob'], ascending=[True,False])\
  .groupby('id').agg(lambda x: x.head(3).tolist())\
  .reset_index().values.tolist()

输出:

[[1, [0.6, 0.5, 0.4]], [2, [0.5, 0.3]]]

答案 1 :(得分:3)

您可以使用groupby和nlargest

df.groupby('id').prob.nlargest(3).reset_index(1,drop = True)

id
1    0.6
1    0.5
1    0.4
2    0.5
2    0.3

对于数组

df1 = df.groupby('id').prob.nlargest(3).unstack(1)#.reset_index(1,drop = True)#.set_index('id')
np.column_stack((df1.index.values, df1.values))

你得到了

array([[ 1. ,  0.5,  0.6,  0.4,  nan,  nan],
       [ 2. ,  nan,  nan,  nan,  0.3,  0.5]])

答案 2 :(得分:1)

如果您要查找数组列的数据框,可以使用applicationContext.xml

np.sort

要检索值df = df.groupby('id').prob.apply(lambda x: np.sort(x.values)[:-4:-1]) df id 1 [0.6, 0.5, 0.4] 2 [0.5, 0.3] 并访问:

reset_index

答案 3 :(得分:1)

[[n, g.nlargest(3).tolist()] for n, g in df.groupby('id').prob]

[[1, [0.6, 0.5, 0.4]], [2, [0.5, 0.3]]]