【问题标题】:Pandas - Adding dataframe with same name using to_hdf doubled file sizePandas - 使用 to_hdf 添加同名数据框使文件大小翻倍
【发布时间】:2017-05-28 10:17:37
【问题描述】:

我是 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

【问题讨论】:

  • 看看this question,应该会有帮助。
  • 我认为这个问题与我的无关
  • 我会在提供更多信息时取消删除我的答案。

标签: python-3.x pandas dataframe hdf5


【解决方案1】:

我可以通过以下方式重现此问题:

原始样本 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 !!! 

【讨论】:

  • 这真是一个具体的解释答案,非常感谢。我尝试了很多来了解自己以及大小技巧,但我无法弄清楚为什么在关闭商店后会引发像上面一样的 ValueError。
  • @bzimor,很高兴我能帮上忙 :-)
猜你喜欢
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 2011-06-25
  • 2019-10-29
  • 2018-09-23
相关资源
最近更新 更多