【问题标题】:Scikit-learn: error in replacing missing dataScikit-learn:替换缺失数据时出错
【发布时间】:2017-04-03 14:09:18
【问题描述】:

我正在尝试通过用平均值替换缺失值来预处理我的数据。

我的代码如下:

#Load the Data 
import numpy as np
data_2 = np.genfromtxt('data.csv', delimiter=',', skip_header=1)

#the missing values in my dataset are identified by value = 0 
#I'm trying to replace the missing values in the third column 
from sklearn.preprocessing import Imputer 
imp = Imputer(missing_values=0, strategy='mean', axis=0)
imp.fit(data_2[:, 2])

它运行但给出了以下警告:

/Users/user1/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)

/Users/user1/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)

但我的主要问题是它没有填充缺失的数据,我打印了拟合前后的数据并且没有变化。

我做错了什么?

更新: 这是我的数据集的几行:
6,148,72,35,0,33.6,0.627,50,1
1,85,66,29,0,26.6,0.351,31,0
8,183,64,0,0,23.3,0.672,32,1
1,89,66,23,94,28.1,0.167,21,0

【问题讨论】:

  • 可以分享几行data.csv吗?
  • 您只在第二列 imp.fit(data_2[:, 2]) 上安装了 imputer。这可能是你的问题吗?毕竟该列可能没有零...
  • 我确信它的值为零..

标签: python python-2.7 scikit-learn


【解决方案1】:
  • 您分享的前几行不包含任何空值,因此难以解释
  • 考虑一下您的数据集的这个稍微更新的版本,以帮助您理解。

    6,148,72,35,0,33.6,0.627,50,1
    1,85,,29,0,26.6,0.351,,
    ,183,64,,0,,0.672,32,1
    1,89,66,23,94,28.1,0.167,21,0
    
  • 有一种简单的方法可以使用库 pandas 来填充缺失值

    #Load Libraries and data
    import pandas as pd
    df = pd.read_csv('data.csv',names=[1,2,3,4,5,6,7,8,9])
    
    #Fill the Null values with the mean
    df = df.fillna(df.mean())
    
  • read_csv 函数中的

    names 参数用于为 csv 文件的列命名

  • fillna() 函数将填充缺失值。

【讨论】:

  • 问题出在我的数据集中,零点等价于 NaN,因此直接计算平均值并填充缺失值是不正确的.. 即假设我有以下值 [0,3 ,4, 5 , 0 ,1] 如果我在计算零点时计算平均值 = 2.167 ,没有它们 = 3.25 所以简单的平均值计算是不正确的.. 如果我使用中位数也是如此
  • 那么,你想要的 [0,3 ,4, 5, 0 ,1] 的平均值是多少
猜你喜欢
  • 2018-03-18
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2016-06-07
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多