Pandas 数据过滤:使用 isin 方法判断元素
是的,可以使用 'in' 方法来判断。在 pandas 中,可以使用 'isin' 方法来过滤数据。'isin' 方法接受一个列表作为参数,然后返回一个布尔值的 Series,表示每个元素是否在列表中。可以将这个 Series 用作过滤条件,来过滤 DataFrame 中的数据。
下面是一个示例:
import pandas as pd
data = {'Name': ['Tom', 'Nick', 'John', 'Alice'],
'Age': [25, 30, 35, 40],
'Gender': ['M', 'M', 'M', 'F']}
df = pd.DataFrame(data)
# 使用 isin 方法过滤数据
filtered_df = df[df['Name'].isin(['Tom', 'John'])]
print(filtered_df)
输出结果为:
Name Age Gender
0 Tom 25 M
2 John 35 M
在上面的示例中,我们使用 'isin' 方法来过滤出名字为 'Tom' 和 'John' 的行。
原文地址: http://www.cveoy.top/t/topic/fR3u 著作权归作者所有。请勿转载和采集!