【问题标题】:Convert two numpy array to dataframe将两个numpy数组转换为数据框
【发布时间】:2018-03-04 21:09:52
【问题描述】:

我想将两个 numpy 数组转换为一个包含两列的 DataFrame。 第一个 numpy 数组“图像”的形状为 102, 1024。 第二个 numpy 数组“标签”的形状为 (1020, )

我的核心代码是:

images=np.array(images)
label=np.array(label)
l=np.array([images,label])
dataset=pd.DataFrame(l)

但事实证明这是一个错误:

ValueError: could not broadcast input array from shape (1020,1024) into shape (1020)

如何将这两个 numpy 数组转换为一个数据框中的两列?

【问题讨论】:

标签: python arrays pandas numpy dataframe


【解决方案1】:

你也可以使用hstack

import pandas as pd
import numpy as np

dataset = pd.DataFrame(np.hstack((images, label.reshape(-1, 1))))

【讨论】:

    【解决方案2】:

    来自工程学,我喜欢创建矩阵的视觉方面。

    matrix_aux = np.vstack([label,images])
    matrix     = np.transpose(matrix_aux)
    df_lab_img = pd.DataFrame(matrix)
    

    需要更多的代码,但也可以使用 Numpy 数组。

    【讨论】:

      【解决方案3】:

      您不能轻松地将它们堆叠起来,尤其是如果您希望将它们作为不同的列,因为您不能在 DataFrame 的一列中插入二维数组,因此您需要将其转换为其他内容,例如 @ 987654321@。

      所以这样的事情会起作用:

      import pandas as pd
      import numpy as np
      images = np.array(images)
      label = np.array(label)
      dataset = pd.DataFrame({'label': label, 'images': list(images)}, columns=['label', 'images'])
      

      这将创建一个有 1020 行和 2 列的 DataFrame,其中第二列中的每个项目都包含长度为 1024 的一维数组。

      【讨论】:

        猜你喜欢
        • 2017-11-09
        • 2020-06-20
        • 1970-01-01
        • 2021-03-26
        • 2019-07-25
        • 2017-05-09
        • 2022-01-12
        • 2019-12-27
        相关资源
        最近更新 更多