如何根据多个条件过滤 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:使用“Or”过滤多个条件
以下代码演示了如何使用或( | ) 运算符过滤 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
您可以在这里找到更多熊猫教程。