|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
pandas的数据清洗——填充NaN数据
1、对于DataFrame里的数据NaN可以使用0来填充,使用fillna函数。
- import pandas as pd
- import numpy as np
- val = np.arange(10, 38).reshape(7, 4)
- col = list("abcd")
- idx = "cake make fake sake wake lake take".split()
- df = pd.DataFrame(val, columns = col, index = idx)
- df["e"] = np.nan
- df.at["make", "e"] = 100
- df["f"] = np.nan
- df.loc["gake"] = np.nan
- print (df)
- df1 = df.fillna(0)
- print (df1)
复制代码
2、前向或后向填充NaN数据的意思是用NaN前一行(方向是往后的)或者后一行的数据填充NaN。
还是使用fillna函数,只不过形参里设定method='ffill'或method='bfill'。
- print ("**1****************************\n", df)
- df2 = df["e"].fillna(method = 'ffill')
- print ("**2****************************\n", df2)
- df2["e"].fillna(method = 'bfill',inplace=True)
- print ("**3****************************\n", df2)
- df2.loc["gake"].fillna(method = 'bfill',inplace=True, axis = 0)
- print ("**4****************************\n", df2)
- df2.loc["gake"].fillna(method = 'bfill',inplace=True, axis = 0)
- print ("**5****************************\n", df2)
- df2.fillna(method = 'ffill',inplace=True, axis = 1)
- print ("**6****************************\n", df2)
复制代码
3、可以给出一个Series数据(label和DataFrame的label有相同的)去填充DataFrame对应行(label)的数据。
- fill = pd.Series([123, 321, 213],index =["cake", "wake", "gake"] )
- df3 = df["e"].fillna(fill)
- df3["f"].fillna(fill,inplace=True)
- print (df3)
复制代码
4、利用插值函数interpolate()对列向的数据进行填值。实现插值填充数据,
那么要求这列上必须得有一些数据才可以,至少2个,会对起点和终点间的NaN进行插值。
- df3["e"].interpolate(inplace=True)
- df3["f"].interpolate(inplace=True)
- print (df3)
复制代码
|
|