我有以下工作代码:
imputer = Imputer(missing_values = 'NaN', strategy='mean', axis = 0)
imputer = imputer.fit(X_train[['Age']])
X_train['Age'] = imputer.transform(X_train[['Age']])
这向我发出以下警告:
A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
当我使用以下行时,我仍然收到相同的警告;这是为什么?:
X_train['Age'] = imputer.transform(X_train[['Age']])
如果我尝试将相同的逻辑应用于所有内容:
imputer = Imputer(missing_values = 'NaN', strategy='mean', axis = 0)
imputer = imputer.fit(X_train.loc[:,'Age'])
X_train.loc[:,'Age'] = imputer.transform(X_train.loc[:, 'Age'])
我收到以下消息,并且 imputer
无法工作:
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
请问,谁能解释一下使用标签将列传递给输入器的正确方法是什么?
我不清楚使用 [['Age']]
和 .loc[:,'Age']
之间的区别,看起来它们有相同的数据,但形状不同。
最佳答案
根据您收到的最后一个错误,当您选择像 imputer = imputer.fit(X_train.loc[:, 'Age'])
这样的数据框列时,您实际上传递了 Serie 到一维的Imputer。
type(X_train['Age'])
pandas.core.series.Series
但是,方法 fit()
要求您向其传递一个二维数组。相反,您可以以返回 Dataframe(即二维)的方式使用列 Age 索引:
type(X_train.iloc[:,2:3])
pandas.core.frame.DataFrame
这样做,您将不会收到尺寸错误。我为了您的目的对此进行了测试并且它有效。
关于python - 使用标签将列传递给输入器的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882008/