[英]Value error: The truth value of an array with more than one element is ambiguous
[英]“The truth value of an array with more than one element is ambiguous” - searching pandas dataframe for NaNs
我正在尝试遍历pandas DataFrame
所有行,并在特定列中查找NaN的第一个实例。 例如:
import pandas as pd
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
for row_index, row in df[:].iterrows():
if pd.isnull(df.ix[:,'one']) == True:
break
但我得到: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我以为我一次只检查DataFrame的一个元素,所以我不知道问题是什么。 任何帮助深表感谢。
干杯。
df.index[ df.one.isnull( ) ][ 0 ]
给出第一行的索引,该列在"one"
列中为null
找到第一行的更有效方法是定义生成器,并获取该生成器的第一个元素,如:
gen = ( idx for idx in df.index if np.isnan( df.one[ idx ] ) )
现在gen.__next__()
将成为第一个索引。
只是要清楚,没有问题,如果你调试你会看到:
ipdb> pd.isnull(df.ix[:,'one'])
a False
b False
c False
d True
所以你确实有多个元素。 真值是不明确的,所以如果你使用.any()你会得到True而使用.all()你会得到False。
注释解决了代码中的错误,我只想清楚地说明任何按名称遇到此主题的人的any()all()行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.