用 pandas 的if语句抛出"ValueError:系列的真值是不明确的". [英] If-statement with pandas throws "ValueError: The truth value of a Series is ambiguous"

查看:56
本文介绍了用 pandas 的if语句抛出"ValueError:系列的真值是不明确的".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看我的数据框中是否有针对某一列的特定字符串,如果有,请启动API.到目前为止的代码:

I am wanting to see if a particular string is present in my dataframe for one column and fire off an API if it is. code so far:

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表达式用于比较标量布尔值.您通过了系列赛.

The reason for this error is because if-else expressions in python are meant to compare scalar boolean values. You passed a Series.

请参见

pandas遵循NumPy约定,在您尝试时会引发错误 将某些内容转换为bool.这会在if陈述中或 使用布尔运算:andornot时.

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'是可选的.


In this example, you can combine them into a single regex pattern 'string2?' which indicates that '2' is optional.

def make_request():
    ...

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

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

If your make_request function returns something, you can call it in a list comp and assign back:

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


另一种选择是使用正则表达式或管道将列表中的字符串连接起来.


Another option is using regex OR pipe to join strings in a list.

import re

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

这篇关于用 pandas 的if语句抛出"ValueError:系列的真值是不明确的".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆