Pandas: 여러 열에 isin을 사용하는 방법


pandas isin() 함수와 함께 다음 메서드를 사용하여 pandas DataFrame의 여러 열을 기반으로 필터링할 수 있습니다.

방법 1: 여러 열이 특정 값과 동일한 경우 필터링

 df = df[df[[' team ', ' position ']]. isin ([' A ',' Guard ']). all (axis= 1 )]

이 특정 예에서는 열이 “A” 이고 위치 열이 “Guard”인 행에 대해 DataFrame을 필터링합니다.

방법 2: 하나 이상의 열이 특정 값과 동일한 필터

 df = df[df[[' team ', ' position ']]. isin ([' A ',' Guard ']). any (axis= 1 )]

이 특정 예에서는 열이 “A” 이거나 위치 열이 “Guard”인 행에 대해 DataFrame을 필터링합니다.

다음 예에서는 다음 pandas DataFrame에서 실제로 각 메서드를 사용하는 방법을 보여줍니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   ' position ': ['Guard', 'Guard', 'Forward', 'Forward',
                                'Guard', 'Guard', 'Forward', 'Forward'],
                   ' points ': [11, 18, 10, 22, 26, 35, 19, 12]})
                   
#view DataFrame
print (df)

  team position points
0 A Guard 11
1 A Guard 18
2 A Forward 10
3 A Forward 22
4 B Guard 26
5 B Guard 35
6 B Forward 19
7 B Forward 12

예 1: 여러 열이 특정 값과 동일한 필터

다음 구문을 사용하여 열이 “A” 이고 위치 열이 “Guard”인 행만 포함하도록 DataFrame을 필터링할 수 있습니다.

 #filter rows where team column is 'A' and position column is 'Guard'
df = df[df[[' team ', ' position ']]. isin ([' A ',' Guard ']). all (axis= 1 )]

#view filtered DataFrame
print (df)

  team position points
0 A Guard 11
1 A Guard 18

열이 “A” 이고 위치 열이 “Guard”인 행만 필터링된 DataFrame에 남아 있습니다.

예 2: 하나 이상의 열이 특정 값과 동일한 필터

다음 구문을 사용하여 열이 “A” 이거나 위치 열이 “Guard”인 행만 포함하도록 DataFrame을 필터링할 수 있습니다.

 #filter rows where team column is 'A' or position column is 'Guard'
df = df[df[[' team ', ' position ']]. isin ([' A ',' Guard ']). any (axis= 1 )]

#view filtered DataFrame
print (df)

  team position points
0 A Guard 11
1 A Guard 18
2 A Forward 10
3 A Forward 22
4 B Guard 26
5 B Guard 35

열이 “A” 이거나 위치 열이 “Guard”인 행만 필터링된 DataFrame에 남아 있습니다.

참고 : pandas isin() 함수에 대한 전체 문서는 여기에서 찾을 수 있습니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas: 피벗 테이블에 필터를 추가하는 방법
Pandas: ‘포함하지 않음’을 필터링하는 방법
Pandas: 특정 문자열이 포함된 행을 필터링하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다