数据预处理-Python

1.若使用树型或线性模型,特征构造时多使用× and /

2.在使用线性模型时可能会出现下列错误:

ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). 
  • 检查是否含有空值,inf(无穷),数值溢出
np.any(np.isnan(mat))
np.all(np.isfinite(mat)) 
  • 解决:

  • 数据输入模型前,填充空值,一般使用df.fillna(df.mean())。

  • 对可能造成无穷大的除法,重新构造函数。A+A.mean()//B+B.mean() or np.aqrt(A+1)/np.sqrt(B)

3.pd.DataFrame中columns参数必须带 [ ]

result = pd.DataFrame({'Id': X_test.Id, 'SalePrice': pred}, columns=['Id', 'SalePrice'])

4.缩放

  • 01缩放
    ### x ^ = x − x m i n x m a x − x m i n \hat x=\frac{x-x_{min}}{x_{max}-x_{min}} x^=xmaxxminxxmin
   min_max_scaler = preprocessing.MinMaxScaler()
   X_train_minmax = min_max_scaler.fit_transform(X_train)
  • Z-Score标准化
    ### x ^ = x − μ σ \hat x=\frac{x-\mu}{\sigma} x^=σxμ
    μ 所有样本数据的均值,σ为所有样本数据的标准差
   scaler = preprocessing.StandardScaler().fit(X_train)
   X_train = scaler.transform(X_train)  

5. one-hot编码

将分类变量(categorical variable)转换为“哑变量矩阵”(dummy matrix)
X_train = pd.get_dummies(X_train)

a = [1, 2, 3, 1]
one_hot = pd.get_dummies(a)
>>>
   1  2  3
0  1  0  0
1  0  1  0
2  0  0  1
3  1  0  0

6.字符分类转数值分类

class_map = {label: idx for idx, label in enumerate(set(data['购买产品']))}
data['购买产品'] = data['购买产品'].map(class_map)
# 也可以自定义class_map = {'A': 1, 'B': 2}

7.协方差与相关系数

Series 有两个方法可以计算协方差与相关系数,方法的主要参数都是另一个 Series。DataFrame 的这两个方法会对列进行两两运算,并返回一个 len(columns) 大小的方阵:
# 相关系数,默认皮尔森
.corr(other, method='pearson', min_periods=1)
# 协方差
.cov(other, min_periods=None)
min_periods 参数为样本量的下限,低于此值的不进行运算。
8.groupby()为并行计算,建议使用此方法
temp = data.groupby(['Id'])
temp['discount'].min()
temp['discount'].max()
temp['discount'].mean()
temp['discount'].var()
temp['discount'].std()

ice_candy = temp['冰糖度'].apply(lambda x: [xxx for xx in x for xxx in xx.split('|')])
# temp 是groupby格式,temp['冰糖度']提取其中一列也是groupby格式,groupby格式循环时,每次循环一个 关键字(此为一个Id),将关键字下的冰糖度,压缩成写成了列表。ice_candy为Series格式,类似字典通过下关键字取值,ice_candy[Id]可得到 这个Id的ice_candy 列表

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值