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

186 阅读2分钟

你可以在pandas中使用**&**符号作为一个 "AND "操作符。

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

df[(condition1) & (condition2)]

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

例子1:在Pandas中使用 "AND "操作符来过滤基于数值的行

假设我们有如下的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      25        5        11
1    A      12        7         8
2    B      15        7        10
3    B      14        9         6
4    B      19       12         6
5    B      23        9         5
6    C      25        9         9
7    C      29        4        12

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

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

        team	points	assists	rebounds
5	B	23	9	5
6	C	25	9	9

唯一返回的行是积分大于20 助攻值等于9的行。

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

假设我们有下面这个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会议列的值等于W的行。

#filter rows based on string values
df[(df.position == 'G') & (df.conference == 'W')]

        team	position  conference points
0	A	G	  W	     11
1	B	G	  W	     8

唯一返回的行是位置列等于G**,**会议列等于W的行。

其他资源

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

如何在Pandas中使用 "OR "运算符
如何通过日期过滤Pandas数据框的行
如何通过列值过滤Pandas数据框