【问题标题】:Efficient storage of large string column in pandas dataframepandas数据框中大字符串列的高效存储
【发布时间】:2015-11-24 17:00:48
【问题描述】:

我有一个大型 pandas 数据框,其中包含一个字符串大小高度倾斜的字符串列。大多数行的字符串长度

我使用 pandas.HDFStorage.append 将此数据帧存储在磁盘上并设置 min_itemsize = 4000。但是,这种方法效率非常低,因为 hdf5 文件非常大,而且我们知道其中大部分是空的。

是否可以为该字符串列的行分配不同的大小?即对字符串较短的行赋值较小的min_itemsize,对字符串较长的行赋值较大的min_itemsize。

【问题讨论】:

  • 不,这在 HDFStore 中是不可能的 ATM。它需要支持可变字符串存储类型,虽然理论上可能在 numpy 中不直接支持。但压缩在这里应该有所帮助。
  • 是数据集的压缩
  • @Jeff 谢谢,很有用。

标签: python-2.7 pandas hdf5


【解决方案1】:

当使用HDFStore存储字符串时,列中字符串的最大长度是该特定列的宽度,可以自定义,参见here

有几个选项可用于处理各种情况。压缩会有很大帮助。

In [6]: df = DataFrame({'A' : ['too']*10000})

In [7]: df.iloc[-1] = 'A'*4000

In [8]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10000 entries, 0 to 9999
Data columns (total 1 columns):
A    10000 non-null object
dtypes: object(1)
memory usage: 156.2+ KB

这些是固定存储,字符串存储为object 类型,所以性能不是特别好;这些商店也不能用于查询/追加。

In [9]: df.to_hdf('test_no_compression_fixed.h5','df',mode='w',format='fixed')

In [10]: df.to_hdf('test_no_compression_table.h5','df',mode='w',format='table')

表格存储非常灵活,但会强制存储固定大小。

In [11]: df.to_hdf('test_compression_fixed.h5','df',mode='w',format='fixed',complib='blosc')

In [12]: df.to_hdf('test_compression_table.h5','df',mode='w',format='table',complib='blosc')

通常使用分类表示可提供运行时和存储效率。

In [13]: df['A'] = df['A'].astype('category') 

In [14]: df.to_hdf('test_categorical_table.h5','df',mode='w',format='table')

In [15]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10000 entries, 0 to 9999
Data columns (total 1 columns):
A    10000 non-null category
dtypes: category(1)
memory usage: 87.9 KB

In [18]: ls -ltr *.h5
-rw-rw-r--     1162080 Aug 31 06:36 test_no_compression_fixed.h5
-rw-rw-r--     1088361 Aug 31 06:39 test_compression_fixed.h5
-rw-rw-r--    40179679 Aug 31 06:36 test_no_compression_table.h5
-rw-rw-r--      259058 Aug 31 06:39 test_compression_table.h5
-rw-rw-r--      339281 Aug 31 06:37 test_categorical_table.h5

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    相关资源
    最近更新 更多