如何在 DataFrame 中索引 np.nan
how to index np.nan in a DataFrame
我在 label
列中创建了一个带有一些 nan
的 DataFrame df
,如何获取 nan
的索引?
我试过df['label'] == np.nan
,但好像不行,而我用sum(df['Adj. Volume'] == 5090527.0)
,却能得到正确的答案,这是怎么回事?为什么 ==np.nan
不起作用?
DataFrame是这样的
使用 isnull
测试 NaN
值:
df[df['label'].isnull()]
这将 return 您 df 中标签为 NaN
的所有行
相等运算符不适用于 NaN
,这就是为什么 == np.NaN
不起作用
NaN
有 属性 那 np.NaN != np.NaN
这是违反直觉的
示例:
In [5]:
s = pd.Series([0,np.NaN, 3])
s
Out[5]:
0 0.0
1 NaN
2 3.0
dtype: float64
In [6]:
s == np.NaN
Out[6]:
0 False
1 False
2 False
dtype: bool
In [7]:
s != s
Out[7]:
0 False
1 True
2 False
dtype: bool
你可以在最后一个例子中看到,如果我们测试 s != s
它是否 returns True
用于 NaN
条目
使用isnull
也得到同样的结果:
In [8]:
s.isnull()
Out[8]:
0 False
1 True
2 False
dtype: bool
然后您可以访问上面的 index
属性以获取索引值:
In [10]:
s[s.isnull()].index
Out[10]:
Int64Index([1], dtype='int64')
我认为你需要 boolean indexing
with isnull
然后 return index
by .index
:
print (df[df.label.isnull()].index)
样本:
df = pd.DataFrame({'A':[1,2,3],
'label':[4,np.nan,np.nan],
'C':[7,8,9]})
print (df)
A C label
0 1 7 4.0
1 2 8 NaN
2 3 9 NaN
print (df[df.label.isnull()].index)
Int64Index([1, 2], dtype='int64')
我在 label
列中创建了一个带有一些 nan
的 DataFrame df
,如何获取 nan
的索引?
我试过df['label'] == np.nan
,但好像不行,而我用sum(df['Adj. Volume'] == 5090527.0)
,却能得到正确的答案,这是怎么回事?为什么 ==np.nan
不起作用?
DataFrame是这样的
使用 isnull
测试 NaN
值:
df[df['label'].isnull()]
这将 return 您 df 中标签为 NaN
相等运算符不适用于 NaN
,这就是为什么 == np.NaN
不起作用
NaN
有 属性 那 np.NaN != np.NaN
这是违反直觉的
示例:
In [5]:
s = pd.Series([0,np.NaN, 3])
s
Out[5]:
0 0.0
1 NaN
2 3.0
dtype: float64
In [6]:
s == np.NaN
Out[6]:
0 False
1 False
2 False
dtype: bool
In [7]:
s != s
Out[7]:
0 False
1 True
2 False
dtype: bool
你可以在最后一个例子中看到,如果我们测试 s != s
它是否 returns True
用于 NaN
条目
使用isnull
也得到同样的结果:
In [8]:
s.isnull()
Out[8]:
0 False
1 True
2 False
dtype: bool
然后您可以访问上面的 index
属性以获取索引值:
In [10]:
s[s.isnull()].index
Out[10]:
Int64Index([1], dtype='int64')
我认为你需要 boolean indexing
with isnull
然后 return index
by .index
:
print (df[df.label.isnull()].index)
样本:
df = pd.DataFrame({'A':[1,2,3],
'label':[4,np.nan,np.nan],
'C':[7,8,9]})
print (df)
A C label
0 1 7 4.0
1 2 8 NaN
2 3 9 NaN
print (df[df.label.isnull()].index)
Int64Index([1, 2], dtype='int64')