【问题标题】:How to Avoid getting NaN when applying One Hot Encoding in Pandas在 Pandas 中应用 One Hot Encoding 时如何避免得到 NaN
【发布时间】:2021-06-06 09:25:53
【问题描述】:

我正在训练一个机器学习模型来预测我所在国家/地区的房价。我不确定如何对我的数据应用一种热编码:所以我从这里复制了代码:One Hot Encoded Labels back to DataFrame

它似乎运作良好,只是我的其他标签现在被 NaN 取代。 Before applying the One Hot Encoding,在我应用一种热编码后,this is the output

我使用的代码如下:

print(ds.head())

categorical_feature_mask = ds.dtypes==object
categorical_cols = ds.columns[categorical_feature_mask].tolist()
labeled_ds = ds[categorical_cols]
enc = OneHotEncoder()
enc.fit(labeled_ds)

onehotlabels = enc.transform(labeled_ds).toarray()

new_columns=list()
for col, values in zip(labeled_ds.columns, enc.categories_):
    new_columns.extend([col + '_' + str(value) for value in values])

ds= pd.concat([ds, pd.DataFrame(onehotlabels, columns=new_columns)], axis='columns')

names = ['location', 'property_type']
ds.drop(names, axis=1, inplace=True)

ds.head()

关于可能导致此问题的任何想法?

【问题讨论】:

  • 我猜是接触部分的问题。确保在连接两个数据框时具有相同的索引。所以使用.reset_index

标签: python pandas machine-learning jupyter-lab


【解决方案1】:

由于索引不同,您遇到了这个问题。

您的 ds 可能有不同的索引(不是从 0 开始且连续),但您的一个热门标签数据帧从 0 开始且连续。

所以当你要进行连接时。由于索引不一样,所以你在那里得到了 nan。

请同时检查形状以确认是否由于索引不匹配导致的问题。

解决:

pd.concat([ds.reset_index(drop=True), pd.DataFrame(onehotlabels, columns=new_columns)], axis='columns')

(如果您想保持与ds 相同的索引)

pd.concat([ds, pd.DataFrame(onehotlabels, columns=new_columns), index=ds.index], axis='columns')

【讨论】:

  • 是的 ds = pd.concat([ds, pd.DataFrame(onehotlabels, columns=new_columns, index=ds.index)], axis='columns') 工作得很好!谢谢你:)
猜你喜欢
  • 2021-04-12
  • 2019-10-11
  • 2021-08-13
  • 1970-01-01
  • 2023-01-10
  • 2020-06-29
  • 2018-03-18
  • 2017-05-11
  • 1970-01-01
相关资源
最近更新 更多