How to efficiently dropna when the NaNs are contained in the index?

I have a series looking like this:

s = pd.Series(
     np.array([0, 0, 1, 1, 2, 2]), 
     index=np.array([  0.,   1.,   2.,   4.,  np.nan,   3.])
)

 0.0    0
 1.0    0
 2.0    1
 4.0    1
NaN     2
 3.0    2
dtype: int64

You'll notice the NaN in the index I want to drop. What's the most efficient way of dropping that row?

Expected result:

0.0    0
1.0    0
2.0    1
4.0    1
3.0    2
Name: 0, dtype: int64

Current approach:

s.reset_index().dropna().set_index('index').squeeze()

3 answers

  • answered 2018-01-14 10:52 jezrael

    Use filtering:

    print (s[s.index.notnull()])
    

    Or similar:

    print (s[~np.isnan(s.index)])
    
    0.0    0
    1.0    0
    2.0    1
    4.0    1
    3.0    2
    dtype: int32
    

  • answered 2018-01-14 10:53 MaxU

    In [22]: s[s.index.notna()]
    Out[22]:
    0.0    0
    1.0    0
    2.0    1
    4.0    1
    3.0    2
    dtype: int32
    

  • answered 2018-01-14 10:55 ayhan

    s[s.index.dropna()]
    
    Out: 
    0.0    0
    1.0    0
    2.0    1
    4.0    1
    3.0    2
    dtype: int64