python - 使用 pandas 的 if 语句抛出 "ValueError: The truth value of a Series is ambiguous"

标签 python python-3.x string pandas

我想查看我的数据框中是否存在某一列的特定字符串,如果存在则触发 API。到目前为止的代码:

if new_df.col1.str.contains('string') == True:
    POST REQUEST
elif new_df.col2.str.contains('string2') == True:
    POST REQUEST

else:
  print('not good')

我不断收到错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

出现此错误的原因是 python 中的 if-else 表达式旨在比较标量 bool 值。您通过了一个系列赛。

请参阅 Pandas Gotchas 的文档部分了解更多信息.

pandas follows the NumPy convention of raising an error when you try to convert something to a bool. This happens in an if-statement or when using the boolean operations: and, or, and not.

<小时/>

在此示例中,您可以将它们组合成一个正则表达式模式 'string2?',这表明 '2' 是可选的。

def make_request():
    ...

for mask in new_df.col1.str.contains(r'string2?'):
    if mask:
        make_request()

如果您的 make_request 函数返回某些内容,您可以在列表组件中调用它并分配回来:

df['response'] = [
    make_request() if m else np.nan for m in new_df.col1.str.contains(r'string2?')]
<小时/>

另一个选项是使用正则表达式或管道来连接列表中的字符串。

import re

words = ['string', 'string2']
for mask in new_df.col1.str.contains('|'.join(map(re.escape, words))):
    ...

关于python - 使用 pandas 的 if 语句抛出 "ValueError: The truth value of a Series is ambiguous",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720098/

相关文章:

python - numpy 字符数组到字符串

python - 在 python 中独立使用 sage 函数

python - Python索引错误: list assignment index out of range ,

当一天有 "0"时,MySQL STR_TO_DATE 似乎失败

c++ - 什么是 C++ 中的标记字符串?

python - 使用 Linux 在控制台模式下启动我自己的程序

python - 使用 Regex 引用组内组

python - 使用 Pandas 计算头对头统计数据

python-3.x - Python => AutoML : XGBoost is not available; skipping it

Python 将字符串转换为固定列数组