我正在阅读一个大型 CSV 文件,其中一列的表示如下。
import pandas as pd
df['col1'] = pd.Series(
["37", "AWESOME House", "Yellow Cottage, 107", "14"], dtype='object'
)
我的代码使用“向量化字符串方法”及时返回所需的数据。
简化代码以说明逻辑的某些部分。
import numpy as np
sth = np.where(
<check condition>,
df['col1'].str.lower(),
df['some_other_column'].whatever()
)
接下来我想检查我的 Series
中的每个值是否包含以下列表中的任何元素。
check_list = ['a', 'b', 'c']
因此预期结果(对于“检查条件”)将是:
False
True
True
False
我试过了
np.where(
np.any([x in df['col1'].str.lower() for x in check_list])
...
但收到错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我怎样才能正确解决我的问题?
答案 0 :(得分:4)
对正则表达式 or
使用 Series.str.contains
和由 case=False
连接的列表值,使用 print (df['col1'].str.contains('|'.join(check_list), case=False))
0 False
1 True
2 True
3 False
Name: col1, dtype: bool
进行不区分大小写的搜索:
regex
没有print (df['col1'].apply(lambda x: any([i in x.lower() for i in check_list])))
0 False
1 True
2 True
3 False
Name: col1, dtype: bool
:
print ([any([i in x.lower() for i in check_list]) for x in df['col1']])
[False, True, True, False]
sscanf