Python 从熊猫系列中删除 NaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20235401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove NaN from pandas series
提问by user1802143
Is there a way to remove a NaN values from a panda series? I have a series that may or may not have some NaN values in it, and I'd like to return a copy of the series with all the NaNs removed.
有没有办法从熊猫系列中删除 NaN 值?我有一个系列,其中可能有也可能没有 NaN 值,我想返回该系列的副本,并删除所有 NaN。
回答by Roman Pekar
>>> 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
updateor even better approach as @DSM suggested in comments, using pandas.Series.dropna():
正如@DSM 在评论中建议的那样更新甚至更好的方法,使用pandas.Series.dropna():
>>> s.dropna()
0 1
1 2
2 3
3 4
5 5
回答by YOBEN_S
A small usage of np.nan ! = np.nan
一个小用法 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
回答by Nand0san
If you have a pandas serie with NaN, and want to remove it (without loosing index):
如果您有一个带有 NaN 的 Pandas 系列,并且想要删除它(不丢失索引):
serie = serie.dropna()
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

