python - 查找包含 NaN 的行的索引

标签 python pandas numpy

在 pandas 数据框中

matrix

我想找到包含 NaN 的行(索引)。

为了在列中查找 NaN,我会这样做

  idx_nan = matrix.columns[np.isnan(matrix).any(axis=1)]

但它不适用于matrix.rows

在行中查找项目的等效项是什么?

最佳答案

我认为你需要DataFrame.isnullanyboolean indexing :

print (df[df.isnull().any(1)].index)

示例:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[np.nan,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B    C  D  E  F
0  1  4  NaN  1  5  7
1  2  5  8.0  3  3  4
2  3  6  9.0  5  6  3

print (df[df.isnull().any(1)].index)
Int64Index([0], dtype='int64')

另一种解决方案:

idx_nan = df[np.isnan(df).any(axis=1)].index
print (idx_nan)   
Int64Index([0], dtype='int64')

idx_nan = df.index[np.isnan(df).any(axis=1)]
print (idx_nan) 

关于python - 查找包含 NaN 的行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40634542/

相关文章:

pandas - 如何更改 tensorflow 的 numpy 数组的数据类型

python - 从数组中随机选择正负数据

python - 从图像opencv python中删除背景颜色

python - Python 数据框中的多重切片

python 字符串如果 x != y 没有按预期工作

python - 用 Python 进行蒙特卡洛模拟 : building a histogram on the fly

Python:在多个进程之间共享一个大型对象字典

python - 如何使 python 3.6 导入文件相对于文件位置?

python - 如何仅保留 pandas 数据帧每组的前 n% 行?

python - python 中的数据帧操作