[英]How to convert string from pandas dataframe to 3-dimensional array in numpy
我已經將包含numpy數組形狀(75,100,3)的pandas數據框導出到csv。 當我導入這個csv文件來獲取我的數據幀時,我的numpy數組是一個字符串。 我在嘗試將此字符串轉換為numpy數組(75,100,3)時遇到了很多問題。
我的字符串是這樣的:
[[[198 113 144], [212 137 157], [213 133 158]
我已經嘗試了幾種方法將其轉換為3d-NUmpy數組但沒有成功。 例如,在代碼段中,我繼續獲得一個字符串數組。
train = pd.read_csv(os.path.join(data_dir, 'trainset.csv'))
train['image'] = train['image'].map(lambda x: x.replace('\n',','))
train['image'] = train['image'].map(lambda x: np.asarray(x))
有人知道一個簡單的方法來處理這個問題嗎?
默認情況下,asarray方法將從數據本身推斷數據類型。 因為你是從csv文件中讀取的,所以它們都是字符串。
您可以使用np.asarray方法的dtype參數來設置數據類型。
import numpy as np
data = [['3','4'],['45','75']]
num_array = np.asarray(data, dtype=np.int)
print(num_array.dtype)
因此,您的代碼只需要更改為:
train = pd.read_csv(os.path.join(data_dir, 'trainset.csv'))
train['image'] = train['image'].map(lambda x: x.replace('\n',','))
train['image'] = train['image'].map(lambda x: np.asarray(x, dtype=np.int))
您可以在哪里將dtype = int更改為np.whatever所需的數據類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.