gpt4 book ai didi

python - 在 Pandas 中连接一个数据集和 OneHotEncoder 的结果

转载 作者:行者123 更新时间:2023-12-01 02:21:04 25 4
gpt4 key购买 nike

让我们考虑 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'

最佳答案

嗯,取决于你如何创建 one-hot 向量。但如果它的排序与原始 DataFrame 相同,并且本身就是一个 DataFrame,则可以在加入之前添加相同的索引:

housing_cat_1hot.index = range(len(housing_cat_1hot))

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

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

已经为您创建了正确的索引

关于python - 在 Pandas 中连接一个数据集和 OneHotEncoder 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47942861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com