Pandas - 使用to_hdf添加相同名称的数据框导致文件大小翻倍

4

我是Pandas模块的新手。我创建了一个数据框并使用to_hdf保存为"dirtree"

df.to_hdf("d:/datatree full.h5", "dirtree")

我重复了上面的步骤。之后,当我检查文件大小时,它加倍了。我想我的第二个数据帧被添加到旧数据帧中,但是在存储中检查数据帧并计算行数显示没有额外的数据帧或行。这怎么可能呢?
用于检查存储的代码:
store = pd.HDFStore('d:/datatree.h5')
print(store)
df = pd.read_hdf('d:/datatree.h5', 'dirtree')
df.text.count() # text is one of the columns in df

看一下这个问题,它应该会有所帮助。 - Fabio Lamanna
我认为这个问题与我的无关,虽然。 - bzimor
1
当我提供更多信息时,我会恢复我的答案。 - piRSquared
1个回答

3
我可以通过以下方式重现此问题:
原始样本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字节

让我们再做一次:

In [149]: df.to_hdf('c:/temp/test_dup.h5', 'x')

文件大小:6992字节 注意:它没有改变

现在让我们打开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字节 注意: 没有改变

让我们再次将DF保存到HDFStore中,但请注意store是打开的:

In [156]: df.to_hdf('c:/temp/test_dup.h5', 'x')

In [157]: store.close()

文件大小:12696字节 # 爆炸!!!

根本原因:

当我们执行: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 !!! 

1
这是一个非常详细的解释,非常感谢。我尝试了很多次自己理解大小技巧,但我无法弄清楚为什么在关闭存储后会引发上述的 ValueError。 - bzimor
@bzimor,很高兴我能帮到你 :-) - MaxU - stand with Ukraine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接