2017-11-11 196 views
-1

非常新的編碼,並試圖編寫一個程序,我將CSV文件中的元素轉換爲具有相同形狀的NumPy數組。如何將文本中的CSV文件轉換爲NumPy中的數組?

我努力在我的CSV文件的內容進行任何操作,因爲我不斷收到以下錯誤消息(和類似):

TypeError: '_io.TextIOWrapper' object is not subscriptable 

TypeError: object of type '_io.TextIOWrapper' has no len() 

AttributeError: '_io.TextIOWrapper' object has no attribute 'split' 

我不知道該怎麼做一個TextIOWrapper還是什麼。謝謝!

+2

請首先向我們展示您所嘗試的內容,而不僅僅是錯誤。 – roganjosh

+0

你有'打開'一個文件,但沒有'讀'任何東西。錯誤意味着您試圖將文件視爲文本行或行列表。 'TextIOWrapper'是打開的文件對象。 – hpaulj

回答

0
import numpy as np 
data = np.genfromtxt('csvfile.csv', delimiter=',') 

使用numpy的genfromtxt()方法並傳遞逗號作爲分隔符,可以將csv文件加載爲numpy數組。

但是,我寧願推薦使用熊貓的read_csv()來讀取文件並創建一個熊貓數據框。如果你願意,你也可以將DataFrame轉換爲一個numpy數組。但是,與numpy數組相比,您可以使用DataFrame輕鬆執行大量有用的數據操作。

import pandas as pd 
data = pd.read_csv('csvfile.csv') # this creates a DataFrame 
data_np = np.array(data) # this creates a numpy array from the DataFrame 
相關問題