python - "The truth value of an array with more than one element is ambiguous"- 在 Pandas 数据框中搜索 NaN

标签 python pandas nan

我正在尝试遍历 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/

相关文章:

python - 如何模拟sys.argv[1 :] on web based python

python - 一次性字典?

python - 关于pandas条件计算的问题

c++ - 将 int32 重新解释为 float

python - 你见过的 Django 中最糟糕的做法

python - 如何做简单、可靠的网络消息传递?

python - 如何在 pandas 数据框中单元格中的列表中插入字符串值?

python - 返回以 pandas dataframe 作为参数的函数的输出

javascript - 为什么 JS 在 : ` + ' any_string'` 中返回 NaN

r - 规模转化产生的NaN