Pandas 数据框获取每组的第一行 [英] Pandas dataframe get first row of each group
本文介绍了Pandas 数据框获取每组的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的熊猫 DataFrame
.
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],'价值':[第一",第二",第二",第一",第二"、第一"、第三"、第四"、第五"、第二"、第五"、第一"、第一第二第三第四第五"]})
我想按 ["id","value"] 将其分组并获取每组的第一行.
id 值0 1 先1 1 秒2 1 秒3 2 第一4 2 秒5 3 第一6 3 第三7 3 第四8 3 第五9 4 秒10 4 第五11 5 第一12 6 第一13 6 秒14 6 第三15 7 第四16 7 第五
预期结果
id 值1个2 第一3 第一4 秒5 第一6 第一7 第四
我尝试了以下只给出DataFrame
的第一行.对此的任何帮助表示赞赏.
在 [25] 中:对于索引,df.iterrows() 中的行:....: df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0])
解决方案
>>>df.groupby('id').first()价值ID1个2 第一3 第一4 秒5 第一6 第一7 第四
如果您需要 id
作为列:
要获取第n条记录,可以使用head():
<预><代码>>>>df.groupby('id').head(2).reset_index(drop=True)id值0 1 先1 1 秒2 2 先3 2 秒4 3 第一5 3 第三6 4 秒7 4 第五个8 5 第一9 6 第一10 6 秒11 7 第四12 7 第五I have a pandas DataFrame
like following.
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
'value' : ["first","second","second","first",
"second","first","third","fourth",
"fifth","second","fifth","first",
"first","second","third","fourth","fifth"]})
I want to group this by ["id","value"] and get the first row of each group.
id value
0 1 first
1 1 second
2 1 second
3 2 first
4 2 second
5 3 first
6 3 third
7 3 fourth
8 3 fifth
9 4 second
10 4 fifth
11 5 first
12 6 first
13 6 second
14 6 third
15 7 fourth
16 7 fifth
Expected outcome
id value
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
I tried following which only gives the first row of the DataFrame
. Any help regarding this is appreciated.
In [25]: for index, row in df.iterrows():
....: df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0])
解决方案
>>> df.groupby('id').first()
value
id
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
If you need id
as column:
>>> df.groupby('id').first().reset_index()
id value
0 1 first
1 2 first
2 3 first
3 4 second
4 5 first
5 6 first
6 7 fourth
To get n first records, you can use head():
>>> df.groupby('id').head(2).reset_index(drop=True)
id value
0 1 first
1 1 second
2 2 first
3 2 second
4 3 first
5 3 third
6 4 second
7 4 fifth
8 5 first
9 6 first
10 6 second
11 7 fourth
12 7 fifth
这篇关于Pandas 数据框获取每组的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文