팬더는 각 그룹 내에서 최고 n 개의 레코드를 얻습니다.
다음과 같이 팬더 DataFrame이 있다고 가정하십시오.
>>> df = pd.DataFrame({'id':[1,1,1,2,2,2,2,3,4],'value':[1,2,3,1,2,3,4,1,1]})
>>> df
id value
0 1 1
1 1 2
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4
7 3 1
8 4 1
다음과 같이 각 ID에 대해 상위 2 개의 레코드가있는 새로운 DataFrame을 얻고 싶습니다.
id value
0 1 1
1 1 2
3 2 1
4 2 2
7 3 1
8 4 1
그룹별로 그룹 내에서 번호 매기기 레코드로 수행 할 수 있습니다.
>>> dfN = df.groupby('id').apply(lambda x:x['value'].reset_index()).reset_index()
>>> dfN
id level_1 index value
0 1 0 0 1
1 1 1 1 2
2 1 2 2 3
3 2 0 3 1
4 2 1 4 2
5 2 2 5 3
6 2 3 6 4
7 3 0 7 1
8 4 0 8 1
>>> dfN[dfN['level_1'] <= 1][['id', 'value']]
id value
0 1 1
1 1 2
3 2 1
4 2 2
7 3 1
8 4 1
그러나이를 위해보다 효과적이고 우아한 접근 방법이 있습니까? 또한 각 그룹 내에서 레코드 수를 정교 하게 접근하는 방법도 있습니다 (예 : SQL 창 함수 row_number () ).
시도해 보았 니 df.groupby('id').head(2)
출력 생성 :
>>> df.groupby('id').head(2)
id value
id
1 0 1 1
1 1 2
2 3 2 1
4 2 2
3 7 3 1
4 8 4 1
(데이터에 따라 사전에 주문 / 정렬해야 할 수도 있습니다)
편집 : 질문자가 언급했듯이 df.groupby('id').head(2).reset_index(drop=True)
multindex를 제거하고 결과를 평평하게하는 데 사용 하십시오.
>>> df.groupby('id').head(2).reset_index(drop=True)
id value
0 1 1
1 1 2
2 2 1
3 2 2
4 3 1
5 4 1
0.14.1 때문에 , 당신은 지금 할 수있는 nlargest
및 nsmallest
A의 groupby
객체 :
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
참고URL : https://stackoverflow.com/questions/20069009/pandas-get-topmost-n-records-within-each-group
'programing tip' 카테고리의 다른 글
Java에 경로 결합 방법이 있습니까? (0) | 2020.06.26 |
---|---|
Node.js에서 cURL이 동일합니까? (0) | 2020.06.26 |
커밋, 커밋 및 푸시, 커밋 및 동기화의 차이점 (0) | 2020.06.26 |
tf.app.run ()은 어떻게 작동합니까? (0) | 2020.06.25 |
테이블 추가 열 구문 변경 (0) | 2020.06.25 |