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/54163856/

相关文章:

python - 两个基本的 Python 字典问题

python-3.x - Python AAD(Azure Active Directory)使用证书进行身份验证

python - 更有效地重新格式化具有不等量空格的文本文件,然后转换为 csv

python - 'str.contains' 不返回数据框中的值

Javascript 将 PascalCase 转换为 underscore_case/snake_case

python - 使用 pygame 和 lambda 实现撤消和重做

python - 迭代目录时出现文件未找到错误

Python:对本地服务器的请求不起作用

javascript - 将字符串与 JavaScript 对象中的键进行比较

python - 从 python 应用程序流式传输 alsa pcm 扬声器输出