2016-10-29 227 views
2

我的數據是88200(行)* 29403(列)(大約14Gb)。數據已經在matlab中使用dlmwrite創建。我試圖用下面的方法來讀取python中的文件。在所有嘗試我已經耗盡內存嘗試將csv文件讀入python時出現內存不足

我的操作系統:Ubuntu 16.04,32GB內存,交換的20Gb Python的2.7.12,熊貓:0.19,GCC 5.4.0

1>使用CSV:

import csv 
import numpy 
filename = 'data.txt' 
raw_data = open(filename, 'rb') 
reader = csv.reader(raw_data, delimiter=',', quoting=csv.QUOTE_NONE) 
x = list(reader) 
data = numpy.array(x).astype('float') 

2A>使用numpy的loadtxt:

import numpy 
filename = 'data.txt' 
raw_data = open(filename, 'rb') 
data = numpy.loadtxt(raw_data, delimiter=",") 

2B>使用numpy的genfromtxt:

import numpy 
x=np.genfromtxt('vectorized_image_dataset.txt',skip_header=0,skip_footer=0,delimiter=',',dtype='float32') 

3>使用pandas.read_csv:

from pandas import * 
import numpy as np 

tp = read_csv(filepath_or_buffer='data.txt', header=None, iterator=True, chunksize=1000) 
df = concat(tp, ignore_index=True) 

在所有它跑出存儲器上述方法。

數據文件已經使用dlmwrite(matlab)創建。一個圖像列表(list.txt)逐一讀取,轉換爲浮點,矢量化並使用dlmwrite存儲。代碼如下:

fileID = fopen('list.txt'); 
N=88200; 
C = textscan(fileID,'%s'); 
fclose(fileID); 

for i=1:N 

A=imread(C{1}{i}); 
% convert the file to vector 
B=A(:); 
% convert the above vector to a row 
D=B'; 
% divide by 256 
%E=double(D)/double(256); 
E=single(D)/single(256); 
dlmwrite('vectorized_image_dataset.txt',E,'-append'); 
clear A;clear B;clear D;clear E; 
end 
+0

你試過逐行讀取文件中的行?用open打開它(「data.txt」,「r」)作爲f:「'然後每次使用for循環處理每行:'for line in f:' – GeckStar

+0

我需要整個數據一個numpy數組,如果我一行一行地讀,我將不得不將對應於新行的數據追加到numpy數組中,這將涉及在每次迭代中調整數組的大小在matlab數組調整大小非常緩慢,我想它會 – user27665

+0

而不是每行添加一行數組嘗試在一個循環(半或四分之一)讀取數據的塊,然後連接數組 –

回答

0

我使用pandas.read_csv解決了這個問題。我把我的data.txt分成四塊,每塊22050行。然後我做了

tp1 = read_csv(filepath_or_buffer='data_first_22050.txt', header=None, iterator=True, chunksize=1000) 
df1 = concat(tp1, ignore_index=True) 
tp2 = read_csv(filepath_or_buffer='data_second_22050.txt', header=None, iterator=True, chunksize=1000) 
df2 = concat(tp2, ignore_index=True)>>> frames=[df1,df2] 
result=concat(frames) 
del frames, df1, df2, tp1, tp2 
tp3 = read_csv(filepath_or_buffer='data_third_22050.txt', header=None, iterator=True, chunksize=1000) 
df3 = concat(tp3, ignore_index=True) 
frames=[result,df3] 
result2=concat(frames) 
del frames, df3, tp3, result 
tp4 = read_csv(filepath_or_buffer='data_fourth_22050.txt', header=None, iterator=True, chunksize=1000) 
df4 = concat(tp4, ignore_index=True) 
frames=[result2,df4] 
result3=concat(frames) 
del frames, tp4, df4, result2 
A=result3.as_matrix() 
A.shape 

(88200,29403)

1
def read_line_by_line(file_path: str): 
    with open(filepath) as file: 
     for line in file: 
      yield line 

也許這一功能將幫助您 - 我不是很熟悉numpy的/大熊貓,但它好像你正試圖一次加載的所有數據,並將其存儲在記憶中。使用上面的函數,您將使用發生器一次只產生一行 - 無需將所有內容存儲在RAM中。

+0

但是人們通常會將數據加載到'numpy'數組或熊貓中,因爲他們想要一次處理所有數據,或者至少需要很多行。像'np.genfromtxt'這樣的函數一行一行地讀取數據,但是它們收集這些行並創建一個數組(列表列表)。例如,他們可能想要對一列或多列進行平均。 – hpaulj