ValueError:系列的真值不明确-检查pandas列中的值

时间:2018-08-08 23:05:02

标签: python-3.x pandas

我正在尝试使用以下代码检查我的panda列是否具有特定值:

if not df['my_col'].str.contains('my_value'):

但是我遇到了以下错误:

  File "/Users/edamame/workspace/git/process/data_stats.py", line 225, in <module>
    if not df['my_col'].str.contains('my_value'):
  File "/Users/edamame/workspace/git/process/venv/lib/python3.4/site-packages/pandas/core/generic.py", line 917, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

任何想法我做错了什么以及如何解决?谢谢!

1 个答案:

答案 0 :(得分:1)

IIUC,您正在检查my_col在该列的任何位置是否包含"my_value"。在这种情况下,请使用.anyif not df['my_col'].str.contains('my_value').any():

或者,您可以使用:if 'my_value' not in df['my_col'].values,它可能比str访问器更快

示例:带有str的方法1

>>> df
     my_col my_col2
0  my_value       x
1         x       x
2         x       x
3  my_value       x

if not df['my_col'].str.contains('my_value').any():
    print('not contained')
else:
    print('contained')

返回:contained

但是:

if not df['my_col2'].str.contains('my_value').any():
    print('not contained')
else:
    print('contained')

返回not contained

示例:使用not in的方法2

或者换一种方式:

if 'my_value' not in df['my_col'].values:
    print('not contained')
else:
    print('contained')