2017-09-23 95 views
2

我想將兩個numpy數組轉換爲一個包含兩列的DataFrame。 第一個numpy數組'圖像'的形狀爲102, 1024。 第二numpy的陣列「標籤」是形狀(1020,)將兩個numpy數組轉換爲數據幀

我的核心代碼:

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數組轉換爲兩列?

+0

的可能的複製的一維數組[組合NumPy數組](https://stackoverflow.com/questions/6740311/combining-numpy-arrays) – Grigoriy

回答

1

您不能輕鬆堆疊它們,特別是如果您希望它們作爲不同的列,因爲您無法在DataFrame的一列中插入二維數組,因此您需要將其轉換爲其他數據,例如list

因此,像這樣的工作:

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']) 

這將創建一個DataFrame有1020行2列,其中在第二列中每個項目包含長度1024

+0

@YZ沒問題。請不要忘記[接受](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)最有用的答案,將問題標記爲已解決。 :) – MSeifert