这里有几件事情你需要注意。
确保您没有在类型“对象”或分类变量上进行估算,您可以像这样查看您的数据:
df = pd.read_csv(filename)
print(df.info(null_counts=True))
最后一列应该是类型
让我们看一个例子:
df = pd.DataFrame({'A' : [1, 2, 2, 2, 'NaN', 3, 4, 5, 6], 'B' : [3, 3, 'NaN', 3, 3, 4, 3, 3, 3]})
输出:
df.head()
A B
---------
0 1 3
1 2 3
2 2 NaN
3 2 3
4 NaN 3
现在让我们看看类型
df.info(null_counts=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 2 columns):
0 9 non-null float64
1 9 non-null float64
dtypes: float64(2)
memory usage: 224.0 bytes
现在估算:
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)
df_imputed = pd.DataFrame(imputer.fit_transform(df))
df_imputed.head()
0 1
-----------
0 1.0 3.0
1 2.0 3.0
2 2.0 3.0
3 2.0 3.0
4 2.0 3.0
现在这一切都很好,但不能在分类上完成(类型对象/字符串)
处理它的一种方法是将分类特征更改为数字,如下所示:
df_with_cat = pd.DataFrame({'A': ['ios', 'android', 'web', 'NaN'], 'B' : [4, 4, 'NaN', 2]})
df_with_cat.head()
A B
-------------
0 ios 4
1 android 4
2 web NaN
3 NaN 2
和信息
df_with_cat.info(null_counts=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 2 columns):
A 4 non-null object
B 4 non-null object
dtypes: object(2)
memory usage: 144.0+ bytes
我们肯定知道 B 是数字,所以让我们这样做:
df_with_cat['B'] = df_with_cat['B'].astype(np.float)
df_with_cat.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 2 columns):
A 4 non-null object
B 3 non-null float64
dtypes: float64(1), object(1)
memory usage: 144.0+ bytes
如果我们使用上面相同的 imputer,我们会得到一个错误(你可以试试)
现在让我们将“A”类别转换为数字:
CATEGORICAL_FEATURES = [
'A',
]
data_dum = pd.get_dummies(df_with_cat, columns=['A'], drop_first=True)
data_dum.head()
B A_android A_ios A_web
---------------------------------
0 4 0 1 0
1 4 1 0 0
2 NaN 0 0 1
3 2 0 0 0
现在我们可以在我们的数据框上从上面运行相同的 Imputer