python - 检查系列是否包含列表中的任何元素

标签 python pandas numpy

我正在读取一个大型 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/

相关文章:

python - Numpy "Fortran"类似 reshape ?

python - 赋值问题,一个 NumPy 函数?

python - 将列表赋值给变量后跟一个逗号相当于访问列表的入口,这种Python特性叫什么名字

Python - 检测值/字符串列表是否是日期、时间、日期时间或两者都不是

Python 服务器有效地处理并发 SQL 请求

Python Pandas - 合并列表中每个项目的数据帧

python - 如何对 Pandas 中的两个领域进行分组?

python - 在 Python 中使用切片更改多个 Numpy 数组元素

python - 类型错误 : 'tuple' object is not callable

python - 在数据框末尾添加 3 个重复列