我有一个如下所示的 pandas DataFrame: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\',\'fi...
如下的 DataFrame
熊猫
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"]})
我想对此进行分组 ["id","value"]
并获取每组的第一行:
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
预期成果:
id value
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
我尝试了以下方法,但只给出了第一行 DataFrame
.
In [25]: for index, row in df.iterrows():
....: df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0])
Pandas 数据框获取每组的第一行
下载声明:
本站所有软件和资料均为软件作者提供或网友推荐发布而来,仅供学习和研究使用,不得用于任何商业用途。如本站不慎侵犯你的版权请联系我,我将及时处理,并撤下相关内容!