3.1数据预处理 python

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy as sp
from scipy import stats ## 用于相关假设检验
## 图像在jupyter notebook中显示
%matplotlib inline
## 显示的图片格式(mac中的高清格式),还可以设置为"bmp"等格式
%config InlineBackend.figure_format = "retina"
## 引入3D坐标系
from mpl_toolkits.mplot3d import Axes3D
## cm模块提供大量的colormap函数
from matplotlib import cm
import matplotlib as mpl
import seaborn as sns

from sklearn.preprocessing import LabelEncoder,OneHotEncoder,normalize,StandardScaler

## 忽略提醒
import warnings
warnings.filterwarnings("ignore")
##3.1数据预处理
    #3.1.1.数据缺失值处理
df=pd.DataFrame(np.random.randn(6,4),columns=list("ABCD"))#生成一个数据框,columns代表列号
df.iloc[2:4,2:4]=np.nan#空数值 iloc:通过行号索引行数据 2:4表示提取2,3行,这里是左闭右开,不包含4
df.iloc[1,0:2]=np.nan
df
ABCD
0-0.4146081.303590-0.2839092.083562
1NaNNaN0.922185-0.037845
20.8545751.439863NaNNaN
30.399861-0.650329NaNNaN
40.2313131.4681901.6261871.012807
50.776413-1.089664-0.600983-0.667237
    #2.检查是否含有缺失值
df.isnull() #T代表有缺失值
ABCD
0FalseFalseFalseFalse
1TrueTrueFalseFalse
2FalseFalseTrueTrue
3FalseFalseTrueTrue
4FalseFalseFalseFalse
5FalseFalseFalseFalse
    #3.使用参数以字典的方式对特征值A进行缺失值填补
df["A"].fillna({'A':0.5},inplace=True) #将A列缺失值用0.5填充
df["A"]
0   -0.801665
1    0.500000
2    1.582609
3    1.303417
4   -0.442469
5    0.188515
Name: A, dtype: float64
df["B"].fillna(method="bfill") #向后插补进行填充,后面的数复制到前一项
0    2.154801
1    1.015598
2    1.015598
3    0.470496
4    1.437253
5    0.262288
Name: B, dtype: float64
df["C"].fillna(method="ffill") #向前插补进行填充
0   -0.129508
1    1.358451
2    1.358451
3    1.358451
4   -1.778825
5   -0.354143
Name: C, dtype: float64
df["D"][df["D"].isnull()] = df["D"].mean()#对变量D使用均值插补
df["D"]
0    0.126941
1    0.012429
2    0.508981
3    0.508981
4    2.337380
5   -0.440826
Name: D, dtype: float64
    #3.1.2.数据标准化和LabelEncoder
from sklearn.preprocessing import LabelEncoder,StandardScaler
Iris = pd.read_csv("D:\Desktop\python在机器学习中的应用\Iris.csv")
print(Iris.head(5)) #查看前五个
   Id  SepalLengthCm  SepalWidthCm  PetalLengthCm  PetalWidthCm      Species
0   1            5.1           3.5            1.4           0.2  Iris-setosa
1   2            4.9           3.0            1.4           0.2  Iris-setosa
2   3            4.7           3.2            1.3           0.2  Iris-setosa
3   4            4.6           3.1            1.5           0.2  Iris-setosa
4   5            5.0           3.6            1.4           0.2  Iris-setosa
Iris.drop("Id", axis=1).boxplot() #删除ID列,箱型图
plt.title("Before standardization Boxplot") #标准化前箱型图
plt.show()

在这里插入图片描述

# 对四个特征进行标准化
scaler = StandardScaler(with_mean=True,with_std=True)#定义标准化操作类scaler
Iris.iloc[:,1:5] = scaler.fit_transform(Iris.iloc[:,1:5])# 对四个特征进行标准化处理
Iris.drop("Id", axis=1).boxplot()
plt.title("After standardizationBoxplot")
plt.show()
#标准化后,取值范围差异较小,集中在0附近

在这里插入图片描述

# LabelEncoder将类别数据从0到n-1开始编码
le = LabelEncoder()
Species = le.fit_transform(Iris.Species)
Species
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
# 生成数据的非线性特征
from sklearn.preprocessing import PolynomialFeatures
X = np.arange(8).reshape(4,2)
X

array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
# degree指特征的最多有几个变量的乘积,interaction_only是否只有交叉项,include_bias表示是否有常数项
pf = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)#(a,b,a**2,ab,b**2)
pf.fit_transform(X)
array([[ 0.,  1.,  0.,  0.,  1.],
       [ 2.,  3.,  4.,  6.,  9.],
       [ 4.,  5., 16., 20., 25.],
       [ 6.,  7., 36., 42., 49.]])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大桃子技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值