여러 조건에서 pandas dataframe을 필터링하는 방법


종종 여러 조건에 따라 Pandas DataFrame을 필터링해야 할 수도 있습니다. 다행히도 이는 부울 연산을 사용하여 쉽게 수행할 수 있습니다.

이 튜토리얼에서는 여러 조건에서 다음 Pandas DataFrame을 필터링하는 방법에 대한 몇 가지 예를 제공합니다.

 import pandas as pd

#createDataFrame
df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'C'],
                   'points': [25, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})

#view DataFrame 
df

        team points assists rebounds
0 to 25 5 11
1 to 12 7 8
2 B 15 7 10
3 B 14 9 6
4 C 19 12 6

예 1: “And”를 사용하여 여러 조건 필터링

다음 코드는 and ( & ) 연산자를 사용하여 DataFrame을 필터링하는 방법을 보여줍니다.

 #return only rows where points is greater than 13 and assists is greater than 7
df[(df. points > 13) & (df. assists > 7)]

        team points assists rebounds
3 B 14 9 6
4 C 19 12 6

#return only rows where team is 'A' and points is greater than or equal to 15
df[(df. team == 'A') & (df. points >= 15)]


        team points assists rebounds
0 to 25 5 11

예 2: ‘또는’을 사용하여 여러 조건 필터링

다음 코드는 또는 ( | ) 연산자를 사용하여 DataFrame을 필터링하는 방법을 보여줍니다.

 #return only rows where points is greater than 13 or assists is greater than 7
df[(df. dots > 13) | (df. assists > 7)]


        team points assists rebounds
0 to 25 5 11
2 B 15 7 10
3 B 14 9 6
4 C 19 12 6

#return only rows where team is 'A' or points is greater than or equal to 15
df[( df.team == 'A') | (df. points >= 15)]

        team points assists rebounds
0 to 25 5 11
1 to 12 7 8
2 B 15 7 10
4 C 19 12 6

예 3: 목록을 사용하여 여러 조건 필터링

다음 코드는 목록에서 행 값이 있는 DataFrame을 필터링하는 방법을 보여줍니다.

 #define a list of values
filter_list = [12, 14, 15]

#return only rows where points is in the list of values
df[df. points . isin (filter_list)]

	team points assists rebounds
1 to 12 7 8
2 B 15 7 10
3 B 14 9 6

#define another list of values
filter_list2 = ['A', 'C']

#return only rows where team is in the list of values
df[df. team . isin (filter_list2)]


        team points assists rebounds
0 to 25 5 11
1 to 12 7 8
4 C 19 12 6

여기서 더 많은 팬더 튜토리얼을 찾을 수 있습니다.

의견을 추가하다

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