Python-数据清洗

重复值处理:
一般采取删除法,但是有些不能删

df.duplicated()
df.duplicated(subset=[],keep='last'/'first')
np.sum(sd.duplicated())
df.dorp_duplicates(subset=[],keep='last'/'first',inplace=true/False)

缺失值:
可以使用删除法,替换法,插值法

统计个数
np.sum(df.isnull())
统计缺失率
df.apply(lambda x:sum(x.isnull())/len(x),axis=0)  #统计列的结果
直接删除
df.dropna(subset=['gender','age'],how='any'/'all',axis=0)  #删除行
df.drop(['age','gender'],axis=1)
填充:中值,均值
df.age.fillna(df.age.mean()/median())
df.gender.fillna(df.gender.mode()[0])--众数填补
df.age.fillna(20)
df.fillna(value={'gender':df.gender.mode()[0],'age':df.age.mean()})

df.fillna(method='ffill'/'bfill')--前项填补,后项填补
df.age.interpolate(method='linear')  线性插值
df.age.interpolate(method='polynomial',order='1')  多项式插值

异常值:

判断:
xbar = df.counts.mean()
xstd = df.counts.std()
正常值分布范围
xbar + 2*xstd
xbar - 2*xstd
# 利用any初步判断
any(df.counts>xbar + 2*xstd)
any(df.counts<xbar - 2*xstd)
#画图判断
df.counts.plot(kind='hist')  #分布图

Q1 = df.counts.quantile(q=0.25)
Q3 = df.counts.quantile(q=0.75)
IQR=Q3-Q1 分位差
df.couts.plot(kind='box') #箱线图
UL=Q3 + 1.5*IQR
#最大值代替
replace = df.counts[sunspots.counts<UL].max()
df.loc[df.counts>UL,'counts']=replace
#分位数替代
p1=df.counts.quantile(0.01)
p2=df.counts.quantile(0.99)
df['counts_new']=df['counts']
df.loc[df['counts_new']>p2,'counts_new']=p2
df.loc[df['counts_new']<p1,'counts_new']=p1

数据离散化(分箱,一般用等频或等宽分段):
pd.cut(series,num/切割点,labels=)
pd.qcut(series,频数列表,labels=)

#等宽分段:

>>> df=pd.DataFrame(np.arange(12).reshape(4,3),columns=list('abc'))
>>>> pd.cut(df.a,2,labels=[1,2])   #第一行是行索引
0    1
1    1
2    2
3    2
>>> a.value_counts()    #统计
2    2
1    2
#等频分段
#法一:
>>> b= pd.Series(np.arange(12))
>>>> w=4
>>> k=[i/w for i in range(w+1)]
>>> k
[0.0, 0.25, 0.5, 0.75, 1.0]
>>> pd.qcut(b,k,labels=[1,2,3,4])   #k:分割的频率
0     1
1     1
2     1
3     2
4     2
5     2
6     3
7     3
8     3
9     4
10    4
11    4
#法二:
>>> w=b.quantile([i/w for i in range(w+1)])
>>> w
0.00     0.00
0.25     2.75
0.50     5.50
0.75     8.25
1.00    11.00
>>> pd.cut(b,w)
0              NaN
1      (0.0, 2.75]
2      (0.0, 2.75]
3      (2.75, 5.5]
4      (2.75, 5.5]
5      (2.75, 5.5]
6      (5.5, 8.25]
7      (5.5, 8.25]
8      (5.5, 8.25]
9     (8.25, 11.0]
10    (8.25, 11.0]
11    (8.25, 11.0]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值