首页 > 解决方案 > 将 pandas 系列转换为 2D numpy 数组

问题描述

我正在尝试在以下系列中使用 OneHot 编码器:

1       redução
2       redução
3       redução
4       redução
         ...   
1969     normal
1970     normal
1971     normal
1972     normal
1973     normal
Length: 1974, dtype: object

但它返回给我以下错误

ValueError: Expected 2D array, got 1D array instead:
array=['redução' 'redução' 'redução' ... 'normal' 'normal' 'normal'].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

我已经尝试了上面的方法,也尝试过np.array(s.values.tolist()),但它也没有用,有人可以帮我解决这个问题吗?

这个系列实际上有 3 个唯一值,这就是我尝试使用 OneHotEncoder 的原因

标签: pythonpandasscikit-learn

解决方案


我使用以下方法对我的 pandas 数据帧进行热编码:

df_dummy = pd.get_dummies(df['col'])

df = pd.concat([df, df_dummy], axis=1)

推荐阅读