Pandas数据帧选择NaN索引

17

我有一个数据框df,其中包含以下内容:

In [10]: df.index.unique()
Out[10]: array([u'DC', nan, u'BS', u'AB', u'OA'], dtype=object)

我可以轻松地选择出 df.ix["DC"]、df.ix["BS"] 等,但是我在选择 nan 索引时遇到了问题。

df.ix[nan], df.ix["nan"], df.ix[np.nan] all won't work.

我该如何选择索引为nan的行?

1
通常情况下,强烈不建议在索引中使用NaN。如果您有多个NaN,则索引不是唯一的,因此许多操作会变得更加低效和复杂。 - Jeff
1个回答

19

一种方法是使用 df.index.isnull() 来确定 NaN 的位置:

In [218]: df = pd.DataFrame({'Date': [0, 1, 2, 0, 1, 2], 'Name': ['A', 'B', 'C', 'A', 'B', 'C'], 'val': [0, 1, 2, 3, 4, 5]}, index=['DC', np.nan, 'BS', 'AB', 'OA', np.nan]); df
Out[218]: 
     Date Name  val
DC      0    A    0
NaN     1    B    1
BS      2    C    2
AB      0    A    3
OA      1    B    4
NaN     2    C    5

In [219]: df.index.isnull()
Out[219]: array([False,  True, False, False, False,  True], dtype=bool)

然后,您可以使用df.loc选择这些行:

In [220]: df.loc[df.index.isnull()]
Out[220]: 
     Date Name  val
NaN     1    B    1
NaN     2    C    5

注意:我的原始答案使用了 pd.isnull(df.index) 而不是 Zero 建议的 df.index.isnull()。最好使用 df.index.isnull(),因为对于不能包含 NaN 的索引类型(如 Int64IndexRangeIndex),isnull 方法会立即返回所有 False 值的数组,而不是盲目地检查索引中的每个项目是否为 NaN 值。

此外,df.loc[df.index.isnull()] -- isnull 方法被添加。 - Zero
@Zero:感谢您的改进! - unutbu
1
如果我们需要删除nan索引行,则可以使用df.loc[df.index.notnull()] - Ketan Mukadam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接