【问题标题】:Join one dataset and the result of OneHotEncoder in Pandas在 Pandas 中加入一个数据集和 OneHotEncoder 的结果
【发布时间】:2017-12-22 14:07:27
【问题描述】:

让我们考虑来自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(最近一次调用最后一次):文件“”,第 1 行,in 结果=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 for df in frames) 文件“/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 for df in frames) A​​ttributeError: 'numpy.ndarray' object has no attribute 'index'

【问题讨论】:

  • 好吧,如果你这样做 to_array 它就会变成一个 numpy 数组。 Join 需要一个数据框或一个系列,而不是一个数组。也许left.join(housing_cat_1hot) 就是你所需要的

标签: python pandas join one-hot-encoding


【解决方案1】:

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

housing_cat_1hot.index = range(len(housing_cat_1hot))

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

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

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

【讨论】:

    【解决方案2】:

    如果你想加入两个数组(假设 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()
    

    【讨论】:

      【解决方案3】:

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

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

      (20640, 15)

      【讨论】:

      • 列名怎么样?
      猜你喜欢
      • 2018-05-21
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 2011-01-14
      • 2023-04-01
      • 2017-03-15
      • 2017-08-10
      • 1970-01-01
      相关资源
      最近更新 更多