我想查看我的数据框中是否存在某一列的特定字符串,如果存在则触发 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
, andnot
.
在此示例中,您可以将它们组合成一个正则表达式模式 '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/