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

Join one dataset and the result of OneHotEncoder in Pandas

让我们考虑来自 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 之间进行 JOIN?

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

Traceback (most recent call last): File "", line 1, in result = left.join(right) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py", line 5293, in join rsuffix=rsuffix, sort=sort) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py", line 5323, in _join_compat can_concat = all(df.index.is_unique for df in frames) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py", line 5323, in can_concat = all(df.index.is_unique for df in frames) AttributeError: 'numpy.ndarray' object has no attribute 'index'

好吧,取决于你如何创建单热向量。 但是如果和你原来的DataFrame一样排序,而且本身就是一个DataFrame,你可以在join之前添加相同的索引:

housing_cat_1hot.index = range(len(housing_cat_1hot))

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

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

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

如果你想连接两个数组(假设housing_cat_1hot和住房都是数组),你可以使用

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()

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

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

(20640, 15)