2024-04-26 19:16:00 发布
网友
假设Python中有一个如下所示的数据帧:
df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']})
或者,以表格形式:
ids vals aball 1 bball 2 cnut 3 fball 4
如何筛选包含关键字“ball”的行?例如,输出应为:
ids vals aball 1 bball 2 fball 4
>>> mask = df['ids'].str.contains('ball') >>> mask 0 True 1 True 2 False 3 True Name: ids, dtype: bool >>> df[mask] ids vals 0 aball 1 1 bball 2 3 fball 4
In [3]: df[df['ids'].str.contains("ball")] Out[3]: ids vals 0 aball 1 1 bball 2 3 fball 4
df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1
逐步说明(从内到外):
df['ids']
ids
pandas.Series
df['ids'].str
lower
contains
df['ids'].str.contains('ball')
True
False
df[df['ids'].str.contains('ball')]
na = False
逐步说明(从内到外):
df['ids']
选择数据帧的ids
列(从技术上讲,对象df['ids']
是pandas.Series
类型)df['ids'].str
允许我们将向量化字符串方法(例如,lower
,contains
)应用于序列df['ids'].str.contains('ball')
检查序列中的每个元素,以确定元素值是否将字符串“ball”作为子字符串。结果是一系列布尔值,表示True
或False
关于“ball”子串的存在李>df[df['ids'].str.contains('ball')]
将布尔“掩码”应用于数据帧,并返回包含适当记录的视图李>na = False
从考虑中删除NA/NaN值;否则,可能会返回ValueError李>相关问题 更多 >
编程相关推荐