pandas Python ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51897638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:57:25  来源:igfitidea点击:

Python ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

pythonpandas

提问by borfo

When I run the following code:

当我运行以下代码时:

if df.loc[df['state_code'].isin(['12','09'])]:

It gives this error:

它给出了这个错误:

ValueError: The truth value of a Series is ambiguous.
Use a.empty, a.bool(), a.item(), a.any() or a.all()

ValueError:系列的真值不明确。
使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

What is wrong here?

这里有什么问题?

回答by ted

The issue tells you that the Seriesreturned by your operation holds no intrinsic truth value. Indeed, the operation will always return something and you have to chose what you actually want:

该问题告诉Series您操作返回的值没有内在真值。事实上,操作总是会返回一些东西,你必须选择你真正想要的:

  • if anyof the returned values is true, meaning there exists an element in dfwhich is in ['12','09']
  • if allof the returned values are true, meaning all elements in dfare in ['12','09']
  • if the returned Seriescontains any element, meaning not empty
  • 如果任何返回值是真实的,这意味着存在一个元件在df其在['12','09']
  • 如果所有返回值都为真,则意味着所有元素df都在['12','09']
  • 如果返回的Series包含任何元素,则表示不empty

So:

所以:

if not df.loc[df['state_code'].isin(['12','09'])].empty:

or

或者

if df.loc[df['state_code'].isin(['12','09'])].any():

or

或者

if df.loc[df['state_code'].isin(['12','09'])].all():

Check out the documentation

查看文档

For more help, provide a minimal working example of your code

如需更多帮助,请提供代码的最小工作示例