2016-05-14 33 views
1

我有一個3GB的CSV文件。我試圖用Pandas將它保存爲HDF格式,這樣我可以更快地加載它。熊貓HDF限制CSV文件的行數

import pandas as pd 
import traceback 

df_all = pd.read_csv('file_csv.csv', iterator=True, chunksize=20000) 

for _i, df in enumerate(df_all): 
    try: 
     print ('Saving %d chunk...' % _i, end='') 
     df.to_hdf('file_csv.hdf', 
        'file_csv', 
        format='table', 
        data_columns=True) 
     print ('Done!') 
    except: 
     traceback.print_exc() 
     print (df) 
     print (df.info()) 

del df_all 

原始的CSV文件有大約300萬行,這反映了這段代碼的輸出。最後一行輸出是:保存167塊...完成! 這意味着:167 * 20000 = 3.340.000行

我的問題是:

df_hdf = pd.read_hdf('file_csv.hdf') 
df_hdf.count() 

=> 4613行

和:

item_info = pd.read_hdf('ItemInfo_train.hdf', where="item=1") 

沒有返回值,甚至我確保原始文件中的「項目」列有一個等於1的條目。

什麼可能是錯的?

+0

可以顯示從'輸出df_hdf.info()''count'計數非楠觀察其數量不一定與您需要append = True的行數 – EdChum

+0

相同 – Jeff

回答

0

使用append=True來告訴to_hdf將新塊添加到相同的文件。

df.to_hdf('file_csv.hdf', ..., append=True) 

否則,每次調用覆蓋以前的內容,只有最後一個塊將被保存在file_csv.hdf


import os 
import numpy as np 
import pandas as pd 

np.random.seed(2016) 
df = pd.DataFrame(np.random.randint(10, size=(100, 2)), columns=list('AB')) 
df.to_csv('file_csv.csv') 
if os.path.exists('file_csv.hdf'): os.unlink('file_csv.hdf') 
for i, df in enumerate(pd.read_csv('file_csv.csv', chunksize=50)): 
    print('Saving {} chunk...'.format(i), end='') 
    df.to_hdf('file_csv.hdf', 
       'file_csv', 
       format='table', 
       data_columns=True, 
       append=True) 
    print('Done!') 
    print(df.loc[df['A']==1]) 
print('-'*80) 
df_hdf = pd.read_hdf('file_csv.hdf', where="A=1") 
print(df_hdf) 

打印

Unnamed: 0 A B 
22   22 1 7 
30   30 1 7 
41   41 1 9 
44   44 1 0 
19   69 1 3 
29   79 1 1 
31   81 1 5 
34   84 1 6 

使用append=True告訴to_hdf新塊追加到同一個文件。否則,只有最後一塊保存在file_csv.hdf

import os 
import numpy as np 
import pandas as pd 

np.random.seed(2016) 
df = pd.DataFrame(np.random.randint(10, size=(100, 2)), columns=list('AB')) 
df.to_csv('file_csv.csv') 
if os.path.exists('file_csv.hdf'): os.unlink('file_csv.hdf') 
for i, df in enumerate(pd.read_csv('file_csv.csv', chunksize=50)): 
    print('Saving {} chunk...'.format(i), end='') 
    df.to_hdf('file_csv.hdf', 
       'file_csv', 
       format='table', 
       data_columns=True, 
       append=True) 
    print('Done!') 
    print(df.loc[df['A']==1]) 
print('-'*80) 
df_hdf = pd.read_hdf('file_csv.hdf', where="A=1") 
print(df_hdf) 

打印

Unnamed: 0 A B 
22   22 1 7 
30   30 1 7 
41   41 1 9 
44   44 1 0 
19   69 1 3 
29   79 1 1 
31   81 1 5 
34   84 1 6