如何在Pandas中使用 "OR "运算符(附例子)

263 阅读2分钟

你可以在pandas中使用|符号作为一个 "OR "运算符。

例如,你可以使用下面的基本语法来过滤pandas DataFrame中满足条件1条件2的行:

df[(condition1) | (condition2)]

下面的例子展示了如何在不同的情况下使用这个 "OR "运算符:

例1:使用 "OR "运算符在Pandas中基于数值过滤行

假设我们有如下的pandas数据框架:

import pandas as pd

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

#view DataFrame
print(df)

  team  points  assists  rebounds
0    A      18        5        11
1    B      22        7         8
2    C      19        7        10
3    D      14        9         6
4    E      14       12         6
5    F      11        9         5
6    G      20        9         9
7    H      28        4        12

我们可以使用下面的语法来过滤DataFrame中积分列的值大于20助攻列的值等于9的行:

#filter rows where points > 20 or assists = 9
df[(df.points > 20) | (df.assists == 9)]

     team   points assists  rebounds
1	B	22	 7	   8
3	D	14	 9	   6
5	F	11	 9	   5
6	G	20	 9	   9
7	H	28	 4	  12

只返回积分大于20助攻大于9的行。

例2:在Pandas中使用 "OR "操作符来过滤基于字符串值的行

假设我们有下面这个pandas数据框架:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'position': ['G', 'G', 'F', 'F', 'C', 'F', 'C', 'C'],
                   'conference': ['W', 'W', 'W', 'W', 'E', 'E', 'E', 'E'],
                   'points': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

  team position conference  points
0    A        G          W      11
1    B        G          W       8
2    C        F          W      10
3    D        F          W       6
4    E        C          E       6
5    F        F          E       5
6    G        C          E       9
7    H        C          E      12

我们可以使用以下语法来过滤DataFrame中位置列的值等于G位置列的值等于F球队列的值等于H的行:

#filter rows based on string values
df[(df.team == 'H') | (df.position == 'G') | (df.position == 'F')]

     team position conference points
0	A	 G	    W	  11
1	B	 G	    W	   8
2	C	 F	    W	  10
3	D	 F	    W	   6
5	F	 F	    E	   5
7	H	 C	    E	  12

返回的行只有满足我们指定的三个条件中至少一个的行。

其他资源

下面的教程解释了如何在pandas中执行其他常见操作:

如何通过列值过滤pandas数据框架
如何通过日期过滤pandas数据框架的行
如何根据多个条件过滤pandas数据框架