python - 值错误: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' , 'occurred at index 0')

标签 python pandas

我的功能如下

def fu1():
    return ("func1")

def fu2():
    return ("func2")

我的代码如下

def test_func(x):
    if (df['response'].str['detected'] == True & df['response_url1'].str['is_doc1'] == True):
        fu1()
    elif (df['response'].str['detected'] == True & df['response_url2'].str['is_doc1'] == True):
        fu2()
    else:
        return ("oops no response")

应用函数时

df.compare = df.apply(test_func,axis = 1)

出现以下错误

ValueError: ('Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。', '发生于索引 0')

df['响应'].str['检测到']

0    True
1    True
2    True
3    True
Name: response, dtype: bool

添加示例数据(head(2))

response,response_url1,response_url2
{'detected': True, 'bool': True}, {'is_doc1': False, 'is_doc2': True},{'is_doc1': True, 'is_doc2': True}
{'detected': False, 'bool': True},{'is_doc1': True, 'is_doc2': True},{'is_doc1': False, 'is_doc2': True}

预期结果 df.compare = func2哎呀没有响应

最佳答案

假设所有这些表达式都计算为 bool 系列',就像您的单个示例一样 - 尝试

def test_func(x):
    if df['response'].str['detected'].all() and df['response_url'].str['is_doc1'].all():
        fu1()
    elif (df['response'].str['detected'].all() and df['response_url2'].str['is_doc1'].all():
        fu2()
    else:
        return ("oops no response")

def test_func(x):
    q = df['response'].str['detected'] == df['response_url'].str['is_doc1']
    r = (df['response'].str['detected'] == df['response_url2'].str['is_doc1']

    if q.all():
        fu1()
    elif r.all():
        fu2()
    else:
        return ("oops no response")

或使用.equals()

def test_func(x):
    if df['response'].str['detected'].equals(df['response_url'].str['is_doc1']):
        fu1()
    elif df['response'].str['detected'].equals(df['response_url2'].str['is_doc1']):
        fu2()
    else:
        return ("oops no response")

关于python - 值错误: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' , 'occurred at index 0'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59449260/

相关文章:

python - 在Python中将字典格式的txt文件转换为excel

python - 将字典的字符串表示形式转换为实际的字典

python - 在 python 中追加表(不同的行号)以实现可视化目的

Python Pandas DataFrame 仅存储一个数字?

python - 两个 Pandas 列的字符串连接

python - 如何批量训练具有多个输入的模型?

c++ - scons ParseConfig 在 Windows 上使用 wx-config 时行为不正确

python - 无法使用boto连接aws s3 bucket

python - 如何获取任何 python 方法的参数?

python - DataFrame .loc 泄漏内存