source

Panda의 데이터 프레임은 각 그룹의 첫 번째 행을 가져옵니다.

bestscript 2022. 11. 1. 21:41

Panda의 데이터 프레임은 각 그룹의 첫 번째 행을 가져옵니다.

나는 판다를 키운다.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])
>>> 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()와 동일합니다).

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

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

사용하는 것이 좋습니다..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

에서 실행할 수 있는 각 그룹의 첫 번째 행만 필요한 경우 함수 기본 방식에 주의하십시오.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

어쩌면 이게 네가 원하는 것일지도 몰라

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

"first"는 데이터 프레임이 이미 원하는 대로 정렬되었음을 의미합니다.

내가 하는 일은:

df.groupby('id').agg('first') "first"는 데이터 프레임을 원하는 대로 정렬했음을 의미합니다.내가 하는 일은:

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

이 점을 고려했을 때'id'열은 다음과 같은 숫자 유형입니다.int32/int64, 다음과 같이 사용할 수도 있습니다.

[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

이 경우,index그리고.id열은 필요 없습니다.

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

요소의 인덱스 목록을 받아들이는 방법을 사용하여 다음을 선택할 수 있습니다.

df.groupby('id').take([0])

언급URL : https://stackoverflow.com/questions/20067636/pandas-dataframe-get-first-row-of-each-group