你可以使用以下方法根据多个条件来选择pandas DataFrame的行:
方法1:选择满足多个条件的行
df.loc[((df['col1'] == 'A') & (df['col2'] == 'G'))]
方法2:选择符合多个条件之一的行
df.loc[((df['col1'] > 10) | (df['col2'] < 8))]
下面的例子展示了如何在实践中使用这些方法中的每一个,即以下的pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'position': ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
df
team position assists rebounds
0 A G 5 11
1 A G 7 8
2 A F 7 10
3 A F 9 6
4 B G 12 6
5 B G 9 5
6 B F 9 9
7 B F 4 12
方法1:选择满足多个条件的行
下面的代码显示了如何在DataFrame中只选择团队等于 "A "且位置等于 "G "的行:
#select rows where team is equal to 'A' and position is equal to 'G'
df.loc[((df['team'] == 'A') & (df['position'] == 'G'))]
team position assists rebounds
0 A G 5 11
1 A G 7 8
在DataFrame中只有两行符合这两个条件。
方法2:选择满足多个条件之一的行
下面的代码显示了如何在DataFrame中只选择助攻大于10或篮板小于8的行:
#select rows where assists is greater than 10 or rebounds is less than 8
df.loc[((df['assists'] > 10) | (df['rebounds'] < 8))]
team position assists rebounds
3 A F 9 6
4 B G 12 6
5 B G 9 5
在DataFrame中只有三条行同时满足这两个条件。
注意:在这两个例子中,我们根据两个条件来过滤行,但使用**&和|**操作符,我们可以根据我们想要的条件来过滤。
其他资源
下面的教程解释了如何在pandas中执行其他常见操作: