我有一个3GB的CSV文件。我试着用Pandas将它保存为HDF格式,这样我就可以更快地加载它。
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 chunk...Done!也就是说: 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")不返回任何内容,即使我确信"item“列在原始文件中有一个等于1的条目。
有什么不对的?
发布于 2016-05-14 15:56:05
使用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 6https://stackoverflow.com/questions/37228192
复制相似问题