Pandas 数据过滤:使用 ~ 运算符实现 'not in' 功能
Pandas 数据过滤:使用 ~ 运算符实现 'not in' 功能
在 Pandas 中,您可以使用 ~ 运算符结合 isin() 方法实现类似 SQL 中 'not in' 的功能,用于过滤 DataFrame 中的数据。
代码示例:
import pandas as pd
data = {'Name': ['Tom', 'Nick', 'John', 'Alice'],
'Age': [30, 25, 35, 28],
'Country': ['USA', 'Canada', 'UK', 'Australia']}
df = pd.DataFrame(data)
# 使用 ~ 运算符进行过滤
filtered_df = df[~df['Country'].isin(['USA', 'UK'])]
print(filtered_df)
输出结果:
Name Age Country
1 Nick 25 Canada
3 Alice 28 Australia
代码解释:
- 我们首先创建一个示例 DataFrame
df。 - 然后,我们使用
df['Country'].isin(['USA', 'UK'])选择 'Country' 列中包含 'USA' 或 'UK' 的行。 ~运算符对结果进行取反,选择 'Country' 列中不包含 'USA' 或 'UK' 的行。- 最后,我们将过滤后的结果存储在
filtered_df中并打印出来。
通过使用 ~ 运算符和 isin() 方法,您可以轻松地过滤 Pandas DataFrame 中的数据,实现类似 'not in' 的功能。
原文地址: http://www.cveoy.top/t/topic/fR3w 著作权归作者所有。请勿转载和采集!