无法从熊猫系列中移除NaN

时间:2015-10-26 18:15:56

标签: pandas ipython-notebook

我知道这个问题之前已被多次询问过,但我发现的所有解决方案似乎都不适合我。我无法从我的pandas Series或DataFrame中删除NaN值。

首先,我尝试直接从DataFrame中删除,就像在文档中的I / O 7和8中那样(http://pandas.pydata.org/pandas-docs/stable/missing_data.html

In[1]:
df['salary'][:5]
Out[1]:
0    365788
1    267102
2    170941
3       NaN
4    243293

In [2]:
pd.isnull(df['salary'][:5])
Out[2]:
0    False
1    False
2    False
3    False
4    False

我期待第3行显示为True,但事实并非如此。我从DataFrame中删除了系列以再次尝试。

sal = df['salary'][:5]

In [100]:
type(sals)
Out[100]:
pandas.core.series.Series

In [101]:    
sal.isnull()
Out[101]:
0    False
1    False
2    False
3    False
4    False
Name: salary, dtype: bool

In [102]:    
sal.dropna()
Out[102]:
0    365788
1    267102
2    170941
3       NaN
4    243293
Name: salary, dtype: object

有人可以告诉我我做错了什么吗?我正在使用IPython Notebook 2.2.0。

1 个答案:

答案 0 :(得分:4)

列的数据类型为object,它告诉我它可能包含字符串而不是数值。尝试转换为浮动:

>>> sa1 = pd.Series(["365788", "267102", "170941", "NaN", "243293"])
>>> sa1
0    365788
1    267102
2    170941
3       NaN
4    243293
dtype: object

>>> sa1.isnull()
0    False
1    False
2    False
3    False
4    False
dtype: bool

>>> sa1 = sa1.astype(float)
>>> sa1.isnull()
0    False
1    False
2    False
3     True
4    False
dtype: bool
相关问题