以下是代码片段,
from sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import OneHotEncoderct = ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[2,3,4])],remainder='passthrough')X = np.array(ct.fit_transform(x_data))X.shape
我得到的形状输出如下
()
当我尝试打印X时,得到的输出如下
array(<8820x35 sparse matrix of type '<class 'numpy.float64'>' with 41527 stored elements in Compressed Sparse Row format>, dtype=object)
现在当我尝试将这个数组转换为DataFrame时
X = pd.DataFrame(X)
我得到以下错误
ValueError: Must pass 2-d input
如何将我的NumPy数组转换为DataFrame?
回答:
看起来
ct.fit_transform(x_data)
产生了一个稀疏矩阵。
np.array(...)
只是将其包装在一个对象类型数组中。
array(<8820x35 sparse matrix of type '<class 'numpy.float64'>' with 41527 stored elements in Compressed Sparse Row format>, dtype=object)
使用toarray
或A
将其正确转换为NumPy数组:
X = ct.fit_transform(x_data).A