将两个numpy数组转换为dataframe

时间:2017-09-23 11:28:57

标签: python arrays pandas numpy dataframe

我想将两个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数组转换为一个数据帧中的两列?

1 个答案:

答案 0 :(得分:6)

您无法轻松堆叠它们,特别是如果您希望它们作为不同的列,因为您无法在DataFrame的一列中插入2D数组,因此您需要将其转换为其他内容,例如{ {1}}。

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

list

这将创建一个包含1020行和2列的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']) ,其中第二列中的每个项目都包含长度为1024的1D数组。