我正在读取一个大型 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().
我怎样才能正确解决我的问题?
最佳答案
使用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
没有正则表达式
:
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]
关于python - 检查系列是否包含列表中的任何元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67700318/