假设我有这个数据框
pd.DataFrame([[1,np.nan,np.nan],[np.nan,np.nan,np.nan],[np.nan,6,np.nan]])
函数应该返回元组数组:
[(0,0), (2,1)]
最佳答案
您可以使用 numpy 函数 isnan
和 where
:
>>> df = pd.DataFrame([[1,np.nan,np.nan],[np.nan,np.nan,np.nan],[np.nan,6,np.nan]])
>>> np.where(~np.isnan(df))
(array([0, 2]), array([0, 1]))
要按照所示的确切方式获取数据:
>>> inds = np.where(~np.isnan(df))
>>> zip(*inds)
[(0, 0), (2, 1)]
使用 pandas 内置函数,您必须对所有系列应用 notnull()
,然后无论如何调用一个 numpy 函数到 DataFrame。
编辑:显然 pandas 在 0.13 中有一个用于数据帧的 notnull
函数,您可以将所有 ~np.isnan(df)
替换为 df.notnull()
如果你愿意的话。
关于python - 检索非 nan 值的 (index,column) 元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361666/