如果您想过滤列值中包含字符串的行,可以使用类似的内容data.sample_id.str.contains('hph')(之前回答过:检查 pandas dataframe 列中的字符串是否在 list 中,或Check if string is in a pandas dataframe) 。
但是,我的查找列包含空单元格。因此,str.contains()产生NaN值,并且在索引时出现值错误。
`ValueError: cannot index with vector containing NA / NaN values``
Run Code Online (Sandbox Code Playgroud)
什么有效:
# get all runs
mask = [index for index, item in enumerate(data.sample_id.values) if 'zent' in str(item)]
Run Code Online (Sandbox Code Playgroud)
str.contains()有没有比这个更优雅、更快的方法(类似)?
您可以将参数设置na为str.contains:False
print (df.a.str.contains('hph', na=False))
Run Code Online (Sandbox Code Playgroud)
使用EdChum样本:
df = pd.DataFrame({'a':['hph', np.NaN, 'sadhphsad', 'hello']})
print (df)
a
0 hph
1 NaN
2 sadhphsad
3 hello
print (df.a.str.contains('hph', na=False))
0 True
1 False
2 True
3 False
Name: a, dtype: bool
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5035 次 |
| 最近记录: |