简体   繁体   English

在Pandas中使用groupby按列值获取前3行

[英]Using groupby in Pandas to get the top 3 rows by column value

I have this dataframe: 我有这个数据框:

    person_code  type   growth   size  ...
0 .         231    32     0.54     32
1 .         233    43     0.12    333
2 .         432    32     0.44     21
3 .         431    56     0.32     23
4 .         654    89     0.12     89
5 .         764    32     0.20    211
6 .         434    32     0.82     90
...

(This dataframe is pretty big, I made a simplification here) (此数据帧非常大,我在这里做了简化)

I want to create one dataframe for each type with the 3 persons with higher "growth", ordered by it. 我想为每种类型创建一个数据框,其中“增长”较高的3个人按其顺序排列。 I want to be able to call it by type. 我希望能够按类型调用它。 In this case, let's use the type 32, so the output df should look something like this: 在这种情况下,让我们使用类型32,因此输出df应该看起来像这样:

    person_code  type   growth   size  ...
6 .         434    32     0.82     90
0 .         231    32     0.54     32
2 .         432    32     0.44     21
...

I understand that it would be something using groupby: 我知道使用groupby会有些事情:

groups=dataframe.groupby('type')

But how could I call the groupby object with the rows where type is 32? 但是,如何调用type为32的行的groupby对象呢? And what would be the best what to separate only the top 3 by growth? 最好的方法是按增长将前三名分开?

IIUC, you don't need a groupby, just query to filter the dataframe then nlargest : IIUC,您不需要groupby,只需query即可过滤数据nlargest然后再选择nlargest

df.query('type == 32').nlargest(3, 'growth')

And, to parameterize 'type' input, you can use this syntax: 并且,要参数化“类型”输入,可以使用以下语法:

in_type = 32

df.query('type == @in_type').nlargest(3, 'growth')

Output: 输出:

     person_code  type  growth  size
6 .          434    32    0.82    90
0 .          231    32    0.54    32
2 .          432    32    0.44    21

Or if you want to use groupby, you can use query to get only the types you need. 或者,如果要使用groupby,则可以使用查询仅获取所需的类型。

type_group_df = df.groupby('type', group_keys=False)\
                  .apply(pd.DataFrame.nlargest,n=3,columns='growth')

To call it, you can use: 要调用它,可以使用:

type_group_df.query('type == 32')

If you've got a string as type it would look like this: 如果您有一个字符串作为类型,它将看起来像这样:

type_group_df.query('type == "brazilian"')

However, if by any chance your column name start with special characters, such as '#', you should use this: 但是,如果您的列名有可能以特殊字符(例如“#”)开头,则应使用以下命令:

type_group_df[type_group_df['#type'] == 32]

Output: 输出:

     person_code  type  growth  size
6 .          434    32    0.82    90
0 .          231    32    0.54    32
2 .          432    32    0.44    21

Query another type (43): 查询另一种类型(43):

type_group_df.query('type == 43')

Output: 输出:

     person_code  type  growth  size
1 .          233    43    0.12   333

You can do this for all of the type s at the same time: 您可以同时对所有type s执行此操作:

df.groupby('type').apply(lambda dft: dft.nlargest(3, 'growth'))

returns 退货

        person_code  type  growth  size
type                                   
32   6          434    32    0.82    90
     0          231    32    0.54    32
     2          432    32    0.44    21
43   1          233    43    0.12   333
56   3          431    56    0.32    23
89   4          654    89    0.12    89

Something like ? 就像是 ?

df.sort_values(['type','person_code']).groupby('type').head(3)
Out[184]: 
   person_code  type  growth  size
0          231    32    0.54    32
2          432    32    0.44    21
6          434    32    0.82    90
1          233    43    0.12   333
3          431    56    0.32    23
4          654    89    0.12    89

Find the indices of the top 3 growth values for each group and feed the level-1 indices into .loc . 找到每个组的前3个增长值的索引,并将第1级索引输入.loc

idx = df.groupby("type")["growth"].nlargest(3).index

# MultiIndex(levels=[[32, 43, 56, 89], [0, 1, 2, 3, 4, 6]],
#           labels=[[0, 0, 0, 1, 2, 3], [5, 0, 2, 1, 3, 4]],
#           names=['type', None])

dftop3 = df.loc[idx.get_level_values(1)]

    person_code type    growth  size
6   434         32       0.82   90
0   231         32       0.54   32
2   432         32       0.44   21
1   233         43       0.12   333
3   431         56       0.32   23
4   654         89       0.12   89

dftop3[dftop3.type == 32]

person_code type    growth  size
6   434      32     0.82    90
0   231      32     0.54    32
2   432      32     0.44    21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM