我可以通过以下方式重现此问题:
原始样本 DF:
In [147]: df
Out[147]:
a b c
0 0.163757 -1.727003 0.641793
1 1.084989 -0.958833 0.552059
2 -0.419273 -1.037440 0.544212
3 -0.197904 -1.106120 -1.117606
4 0.891187 1.094537 100.000000
让我们把它保存到 HDFStore:
In [149]: df.to_hdf('c:/temp/test_dup.h5', 'x')
文件大小:6992 bytes
让我们再做一次:
In [149]: df.to_hdf('c:/temp/test_dup.h5', 'x')
文件大小:6992 bytes 注意:它没有改变
现在让我们打开 HDFStore:
In [150]: store = pd.HDFStore('c:/temp/test_dup.h5')
In [151]: store
Out[151]:
<class 'pandas.io.pytables.HDFStore'>
File path: c:/temp/test_dup.h5
/x frame (shape->[5,3])
文件大小:6992 bytes 注意:它没有改变
让我们再次将 DF 保存到 HDFStore,但请注意 store 已打开:
In [156]: df.to_hdf('c:/temp/test_dup.h5', 'x')
In [157]: store.close()
文件大小:12696 bytes#BOOM !!!
根本原因:
当我们这样做时:store = pd.HDFStore('c:/temp/test_dup.h5') - 它以默认模式 'a'(追加)打开,因此它已准备好修改存储,当您写入同一文件时,但不使用此 store 它会生成复制以保护开放的商店...
如何避免:
开店时使用mode='r':
In [158]: df.to_hdf('c:/temp/test_dup2.h5', 'x')
In [159]: store2 = pd.HDFStore('c:/temp/test_dup2.h5', mode='r')
In [160]: df.to_hdf('c:/temp/test_dup2.h5', 'x')
...
skipped
...
ValueError: The file 'c:/temp/test_dup2.h5' is already opened, but in read-only mode. Please close it before reopening in append mode.
或者更好的方式来管理你的 HDF 文件 - 是使用 store:
store = pd.HDFStore(filename) # it's stored in the `'table'` mode per default !
store.append('key_name', df, data_columns=True)
...
store.close() # don't forget to flush changes to disk !!!