我的功能如下
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/