我正在尝试遍历 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:具有多个元素的数组的真值不明确。使用 a.any() 或 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__()
将成为第一个索引。
关于python - "The truth value of an array with more than one element is ambiguous"- 在 Pandas 数据框中搜索 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20571923/