从熊猫系列中去除 NaN

有没有办法从熊猫系列中去除 NaN 值?我有一个序列,其中可能有一些 NaN 值,也可能没有,我想返回一个删除了所有 NaN 值的序列副本。

123552 次浏览
>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0    1
1    2
2    3
3    4
5    5

update or even better approach as @DSM suggested in comments, using pandas.Series.dropna():

>>> s.dropna()
0    1
1    2
2    3
3    4
5    5

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]:
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)


0      g
1    NaN
2    NaN
3      k
4      s
dtype: object


# the code
ser = ser.dropna()
print(ser)


0    g
3    k
4    s
dtype: object