我有一个熊猫数据框架如下:

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

当前回答

也许这就是你想要的

import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'],   ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)

流行 12 county2 15 county3 65 county4 42 州县78 county2 67 county3 55 county4 31

df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)

> Out[29]: 
                pop
state1 county3   65
       county4   42
       county2   15
state2 county1   78
       county2   67
       county3   55

其他回答

也许这就是你想要的

import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'],   ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)

流行 12 county2 15 county3 65 county4 42 州县78 county2 67 county3 55 county4 31

df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)

> Out[29]: 
                pop
state1 county3   65
       county4   42
       county2   15
state2 county1   78
       county2   67
       county3   55

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

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

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

考虑到'id'列是数字类型,例如int32/int64,也可以使用groupby.rank(),如下所示

[In]: df[df.groupby('value')['id'].rank() == 1]
[Out]:
   id   value
0   1   first
6   3   third
7   3  fourth
8   3   fifth

如果想要重置索引,只需传递.reset_index(),例如

[In]: df[df.groupby('value')['id'].rank() == 1].reset_index()
[Out]:
   index  id   value
0      0   1   first
1      6   3   third
2      7   3  fourth
3      8   3   fifth

如果不需要索引列和id列

[In]: df.drop(['index', 'id'], axis=1, inplace=True)
[Out]:
    value
0   first
1   third
2  fourth
3   fifth

我想“第一”意味着你已经按照你想要的对你的数据帧进行了排序。

我所做的是:

df.groupby (id) .agg(“第一次”) 我想“第一”意味着你已经按照你想要的对你的数据帧进行了排序。 我所做的是:

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

好处是你可以插入任何你想要的函数:

df.groupby('id').agg(['first','last','count']))
     value              
     first    last count
id                      
1    first  second     3
2    first  second     2
3    first   fifth     4
4   second   fifth     2
5    first   first     1
6    first   third     3
7   fourth   fifth     2

输出数据帧有MultiIndex列

MultiIndex([('value', 'first'),
            ('value',  'last'),
            ('value', 'count')],
           )

如果你只需要每个组的第一行,我们可以使用drop_duplicate,注意函数的默认方法keep='first'。

df.drop_duplicates('id')
Out[1027]: 
    id   value
0    1   first
3    2   first
5    3   first
9    4  second
11   5   first
12   6   first
15   7  fourth