Pandas数据帧获取每个组的第一行1

2024-05-08 23:03:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一只熊猫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])

Tags: iniddataframedfforindexvaluerow
3条回答

这将为您提供每个组的第二行(零索引,n(0)与first()相同):

df.groupby('id').nth(1) 

文档:http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group

>>> df.groupby('id').first()
     value
id        
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

如果需要id作为列:

>>> 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

要获取n个第一个记录,可以使用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

如果需要获得第一行,我建议使用.nth(0),而不是.first()

它们之间的区别在于如何处理nan,因此无论这行中的值是什么,.nth(0)都将返回组的第一行,而.first()最终将返回每列中的第一个而不是NaN值。

例如,如果您的数据集是:

df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
            'value'  : ["first","second","third", np.NaN,
                        "second","first","second","third",
                        "fourth","first","second"]})

>>> df.groupby('id').nth(0)
    value
id        
1    first
2    NaN
3    first
4    first

以及

>>> df.groupby('id').first()
    value
id        
1    first
2    second
3    first
4    first

相关问题 更多 >