在Pandas中加入一个数据集和OneHotEncoder的结果

问题描述 投票:1回答:3

让我们来看看this example的房价数据集。

我将整个数据集存储在housing变量中:

housing.shape

(20640, 10)

我也做过一维的OneHotEncoder编码并得到housing_cat_1hot,所以

housing_cat_1hot.toarray().shape

(20640, 5)

我的目标是加入两个变量并将所有内容存储在一个数据集中。

我试过Join with index tutorial,但问题是第二个矩阵没有任何索引。我如何在housinghousing_cat_1hot之间加入?

>>> left=housing
>>> right=housing_cat_1hot.toarray()
>>> result = left.join(right)

回溯(最近一次调用最后一次):文件“”,第1行,结果= left.join(右)文件“/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib /python3.6/pandas/core/frame.py“,第5293行,在连接rsuffix = rsuffix,sort = sort)文件”/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/ 3.6 / lib / python3.6 / pandas / core / frame.py“,第5323行,在_join_compat中can_concat = all(df.index.is_unique用于帧中的df)文件”/usr/local/Cellar/python3/3.6.3 /Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py“,第5323行,在can_concat = all中(df.index.is_unique用于帧中的df)AttributeError:'numpy.ndarray '对象没有属性'索引'

python pandas join one-hot-encoding
3个回答
1
投票

那么,取决于你如何创建一个热矢量。但如果它的排序方式与原始DataFrame相同,并且本身就是DataFrame,则可以在加入之前添加相同的索引:

housing_cat_1hot.index = range(len(housing_cat_1hot))

如果它不是DataFrame,请将其转换为一个。这很简单,只要两个对象的排序方式相同即可

编辑:如果它不是DataFrame,那么:housing_cat_1hot = pd.DataFrame(housing_cat_1hot)

已经为您创建了合适的索引


1
投票

如果你想加入两个数组(假设housing_cat_1hot和housing都是数组),你可以使用

housing = np.hstack((housing, housing_cat_1hot))

虽然OneHotEncode变量的最佳方法是在数组中选择该变量并进行编码。它为您节省了以后加入两者的麻烦

假设您希望在数组中编码的变量的索引是1,

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
le = LabelEncoder()  
X[:, 1] = le.fit_transform(X[:, 1])

onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()

0
投票

感谢@ Elez-Shenhar回答我得到以下工作代码:

OneHot=housing_cat_1hot.toarray()
OneHot= pd.DataFrame(OneHot)
result = housing.join(OneHot)
result.shape

(20640, 15)

© www.soinside.com 2019 - 2024. All rights reserved.