パンダのデータフレームは各グループの最初の行を取得します


137

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

2
私はこの質問がかなり古いことfirst()に気づきましたが、nansに関する動作が非常に驚くべきものであり、ほとんどの人が期待しないものであるため、@ vital_dmlで回答を受け入れることをお勧めします。
user545424

回答:


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

1
どうもありがとう!うまくいきました:)同じ方法で2行目を取得することはできませんか?それも説明できますか?
Nilani Algiriyage 2013年

g = df.groupby(['session'])g.agg(lambda x:x.iloc [0])これも機能しており、2番目の値を取得する方法がわかりませんか?:(
Nilani Algiriyage 2013年

上から数えて行番号top_nを取得し、次にdx = df.groupby( 'id')。head(top_n).reset_index(drop = True)とし、下から数えて行番号を取得するとします。 bottom_n、次にdx = df.groupby( 'id')。tail(bottom_n).reset_index(drop = True)
ケツァルコアトル

3
最後のn行が必要なtail(n)場合は、(デフォルトはn = 5)を使用します(参照)。と混同しないようにlast()、私はその間違いを犯しました。
rocarvaj 2016

groupby('id',as_index=False)id列としても保持
Richard DiSalvo

50

これにより、各グループの2番目の行が表示されます(ゼロインデックス、nth(0)はfirst()と同じ):

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

ドキュメント:http : //pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group


8
たとえば、最初の3つのように複数にする場合は、nth((0,1,2))またはのようなシーケンスを使用しますnth(range(3))
RonanPaixão2016

@RonanPaixão:どういうわけか、範囲を指定するとエラーがスローされます:TypeError: n needs to be an int or a list/set/tuple of ints
平和な

@ピースフル:Python 3を使用していますか?その場合、と入力range(3)しない限り、リストは返されませんlist(range(3))
Ben

41

最初の行を取得する必要.nth(0)がある.first()場合よりも、使用することをお勧めします。

それらの違いは、NaNの処理方法です。そのため.nth(0)、この行の値に関係なく、グループの最初の行を.first()返し、最終的に各列の最初のnot 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

1
いい視点ね。.head(1)また.nth(0)、インデックスを除いて、のように動作するように見えます
Richard DiSalvo

1
もう1つの違いは、nth(0)は元のインデックスを維持する(as_index = Falseの場合)が、first()は維持しないことです。
オレグO

7

多分これはあなたが欲しいものです

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)
                pop
state1 county1   12
       county2   15
       county3   65
       county4   42
state2 county1   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

7

使用できる各グループの最初の行だけが必要な場合はdrop_duplicates、関数のデフォルトメソッドに注目してください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
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.