i有一个熊猫数据框架,该数据框有一些行和列。每列都有一个标题。现在,只要我继续在熊猫中进行数据操作操作,我的可变标头就会保留。但是,如果我尝试SCI-KIT-LEARN LIB的一些数据预处理功能,我最终会丢失所有标题,并且框架仅转换为数字矩阵。
我理解为什么会发生这种情况,因为Scikit-learn将Numpy ndarray作为输出。 Numpy ndarray只是矩阵将没有列名。
但这是它。如果我在数据集上构建了一些模型,即使在初始数据进行了预处理并尝试一些模型之后,我可能还必须执行更多数据操作任务,以运行其他模型以更好地拟合。如果我不知道我可能不知道特定变量的索引是什么,但是不知道要记住变量名称,甚至可以通过使用DF. -Columns查找更容易,因此无法访问列标题。
如何克服?
Edit1:使用样本数据快照进行编辑。
Pclass Sex Age SibSp Parch Fare Embarked
0 3 0 22 1 0 7.2500 1
1 1 1 38 1 0 71.2833 2
2 3 1 26 0 0 7.9250 1
3 1 1 35 1 0 53.1000 1
4 3 0 35 0 0 8.0500 1
5 3 0 NaN 0 0 8.4583 3
6 1 0 54 0 0 51.8625 1
7 3 0 2 3 1 21.0750 1
8 3 1 27 0 2 11.1333 1
9 2 1 14 1 0 30.0708 2
10 3 1 4 1 1 16.7000 1
11 1 1 58 0 0 26.5500 1
12 3 0 20 0 0 8.0500 1
13 3 0 39 1 5 31.2750 1
14 3 1 14 0 0 7.8542 1
15 2 1 55 0 0 16.0000 1
以上基本上是熊猫的数据框架。现在,当我在此数据框架上执行此操作时,它将剥离列标题。
from sklearn import preprocessing
X_imputed=preprocessing.Imputer().fit_transform(X_train)
X_imputed
新数据是numpy数组的,因此列的名称被剥离了。
array([[ 3. , 0. , 22. , ..., 0. ,
7.25 , 1. ],
[ 1. , 1. , 38. , ..., 0. ,
71.2833 , 2. ],
[ 3. , 1. , 26. , ..., 0. ,
7.925 , 1. ],
...,
[ 3. , 1. , 29.69911765, ..., 2. ,
23.45 , 1. ],
[ 1. , 0. , 26. , ..., 0. ,
30. , 2. ],
[ 3. , 0. , 32. , ..., 0. ,
7.75 , 3. ]])
因此,当我在熊猫数据框架上进行一些数据操作时,我想保留列名。
Scikit-learn在大多数情况下确实会剥离列标题,因此随后只需将它们添加回它们即可。在您的示例中,使用
X_imputed
作为sklearn.preprocessing
输出,将X_train
作为原始dataFrame,您可以将列标题重新打开:
X_imputed_df = pd.DataFrame(X_imputed, columns = X_train.columns)
中所述的列名之前,请运行类似的内容(对于列):
X_train=X_train.dropna(axis=1, how='all')
df.dropna在此处描述
from sklearn.impute import SimpleImputer
# Imputation
my_imputer = SimpleImputer()
imputed_X = pd.DataFrame(my_imputer.fit_transform(X))
# Imputation removed column names; put them back
imputed_X.columns = X.columns
Scikit-learn具有get_feature_names()方法。这个想法是从from sklearn import preprocessing as pp
poly = pp.PolynomialFeatures(3, interaction_only=False, include_bias=False)
poly.fit(X_train)
X_test_new=pd.DataFrame(poly.transform(X_test), columns=poly.get_feature_names(X_test.columns))
X_test_new.head()
可以使用keep_empty_features = true来保留所有功能,然后您可以添加原始列名称