您的位置:首页 > 编程语言 > Python开发

【Python数据分析之pandas05】处理缺失化数据

2018-03-18 13:38 239 查看
    首先,Python用.isnull的方法判断对象元素是否为NaN(缺失值)。s1 = pd.Series(['one','two',np.nan,'three'])
s1.isnull()
'''
0 False
1 False
2 True
3 False
dtype: bool
'''    之前提到了一种填充缺失值的方法是重新索引时修改其method属性,这里意思差不多,只是直接用fillna方法填充缺失值:s1 = pd.Series(['one','two',np.nan,'three'])
s1.fillna(method='ffill')
'''
0 one
1 two
2 two
3 three
dtype: object
'''    fillna()还可以通过指定缺失值来填充,值得注意的是,fillna方法默认返回一个新对象:df = pd.DataFrame(np.random.randn(4,4))
df.iloc[:4,1]=np.nan;df.iloc[:2,2]=np.nan
print(df)
'''
         0   1         2         3
0  0.639954 NaN       NaN -1.875799
1  0.141415 NaN       NaN  0.712173
2  1.479268 NaN  0.390988 -0.436616
3  2.143007 NaN  0.535538 -0.582310
'''

print(df.fillna(0))
'''
         0    1         2         3
0  0.882594  0.0  0.000000 -0.235420
1  0.959379  0.0  0.000000 -0.713679
2  0.109616  0.0  0.256728 -0.480367
3  0.234736  0.0 -0.461598  1.340675
'''

print(df)
'''
  0   1         2         3
0 -1.018811 NaN       NaN -1.202366
1  0.709019 NaN       NaN  0.879469
2  1.214638 NaN -0.605073  0.151528
3 -1.057719 NaN -0.856848 -0.040519
'''    *.ix索引的方法现在改成了iloc
    想要原地修改就得修改method属性:df = pd.DataFrame(np.random.randn(4,4))
df.iloc[:4,1]=np.nan;df.iloc[:2,2]=np.nan
print(df)
'''
0 1 2 3
0 0.639954 NaN NaN -1.875799
1 0.141415 NaN NaN 0.712173
2 1.479268 NaN 0.390988 -0.436616
3 2.143007 NaN 0.535538 -0.582310
'''

df.fillna(0,inplace=True)
print(df)
'''
0 1 2 3
0 0.223656 0.0 0.000000 0.160646
1 1.567522 0.0 0.000000 1.202753
2 1.985000 0.0 0.612963 0.792907
3 -0.100812 0.0 1.081931 -0.028931
'''    但是,无论是否修改inplace属性,fillna都会返回一个新的对象,这一点通过检查id就可以证明。
    当然,之前的重新索引reindex的插值方法都可以运用于fillna。

    如果不想进行数据填充,pandas也提供了一些清楚缺失值的方法。

    对于Series
4000
,可以通过dropna或索引的方法清除:
#dropna方法
s = pd.Series([1,2,3,np.nan,np.nan,5])
s.dropna()
'''
0 1.0
1 2.0
2 3.0
5 5.0
dtype: float64

'''

#索引方法
s = pd.Series([1,2,3,np.nan,np.nan,5])
s[s.notnull()]
'''
0 1.0
1 2.0
2 3.0
5 5.0
dtype: float64
'''    DataFrame的清除涉及到行或列的问题,dropna()方法默认清除行:data = pd.DataFrame([[1,6.5,3],[1,np.nan,np.nan],[np.nan,np.nan,np.nan],[np.nan,6.5,3]])
print(data)
'''
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0

'''

print(data.dropna())
'''
0 1 2
0 1.0 6.5 3.0
'''    想要清除列,传入axis=1即可,这里不举例了。
    dropna还有一个重要参数是how='all',传入它则只丢弃全为NA的那些行:
print(data.dropna(how="all"))
'''
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
3 NaN 6.5 3.0
'''    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: