【问题标题】:how to convert sparse numpy array to Dataframe?如何将稀疏 numpy 数组转换为 Dataframe?
【发布时间】:2021-02-21 01:07:20
【问题描述】:

下面是代码sn-p,

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = 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)

现在当我尝试将此数组转换为数据帧时

X = pd.DataFrame(X)

我得到以下错误

ValueError: Must pass 2-d input

如何将我的 numpy 数组转换为数据框?

【问题讨论】:

  • @FadingOrigami 请不要将答案发布为 cmets。您错过了声誉,其他人会认为问题没有得到回答。

标签: arrays python-3.x pandas numpy machine-learning


【解决方案1】:

看起来像

ct.fit_transform(x_data)

产生一个稀疏矩阵。

np.array(...)

只需将其包装在对象 dtype 数组中。

array(<8820x35 sparse matrix of type '<class 'numpy.float64'>'
    with 41527 stored elements in Compressed Sparse Row format>, dtype=object)

使用toarrayA 将其正确转换为numpy 数组:

X = ct.fit_transform(x_data).A

【讨论】:

    【解决方案2】:

    所以首先,将稀疏矩阵从 csr_matrix 转换为普通数组

     X = X.toarray()
     df  = pd.DataFrame(X)
    

    以上应该可以工作

    【讨论】:

    • 我试过你给的方法,但我得到了这样的错误`“AttributeError: 'numpy.ndarray' object has no attribute 'tocsc” 有什么想法吗?
    • 嗨,@pramod 我已经编辑了解决问题的答案。此外,如果上述答案有效,如果您接受正确的答案,我将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2019-02-11
    • 2014-12-21
    相关资源
    最近更新 更多