gpt4 book ai didi

python - 将两个 numpy 数组转换为数据帧

转载 作者:太空狗 更新时间:2023-10-30 00:53:30 25 4
gpt4 key购买 nike

我想将两个 numpy 数组转换为一个包含两列的 DataFrame。第一个 numpy 数组“images”的形状为 102, 1024。第二个 numpy 数组“label”的形状为 (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 数组转换为一个数据帧中的两列?

最佳答案

你不能轻易地堆叠它们,特别是如果你希望它们作为不同的列,因为你不能在 DataFrame 的一列中插入一个二维数组,所以你需要将它转换成其他东西,例如 列表

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

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 的一维数组。

关于python - 将两个 numpy 数组转换为数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com