从python中的groupby对象中选择一个特定的行 [英] selecting a particular row from groupby object in python
问题描述
id mark年份
1 18 2013
1 25 2012
3 16 2014
2 16 2013
1 19 2013
3 25 2013
2 18 2014
假设现在我将上述id by python命令。
grouped = file.groupby(file.id)
我想要一个新文件,只包含行每组最近一年是全年最高的一组。
请让我知道这个命令,我正在尝试使用,但它只会给出布尔表达式。我希望整个行都有最新的一年。
我使用下面的代码拼凑了它:Python:获得具有最大值的行因此,基本上我们可以将'id'列分组,然后调用 transform
'年'列并创建一个布尔指数,其中年份与每个'id'的最大年份值匹配:
在[103]中:
df [df.groupby(['id'])['year']。transform(max)== df ['year']]
Out [ 103]:
标识年份
0 1 18 2013
2 3 16 2014
4 1 19 2013
6 2 18 2014
id marks year
1 18 2013
1 25 2012
3 16 2014
2 16 2013
1 19 2013
3 25 2013
2 18 2014
suppose now I group the above on id by python command.
grouped = file.groupby(file.id)
I would like to get a new file with only the row in each group with recent year that is highest of all the year in the group.
Please let me know the command, I am trying with apply but it ll only given the boolean expression. I want the entire row with latest year.
I cobbled this together using this: Python : Getting the Row which has the max value in groups using groupby
So basically we can groupby the 'id' column, then call transform
on the 'year' column and create a boolean index where the year matches the max year value for each 'id':
In [103]:
df[df.groupby(['id'])['year'].transform(max) == df['year']]
Out[103]:
id marks year
0 1 18 2013
2 3 16 2014
4 1 19 2013
6 2 18 2014
这篇关于从python中的groupby对象中选择一个特定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!