14

我有一个大的 Pandas 数据框(~15GB,83m 行),我有兴趣将其保存为h5(或feather)文件。一列包含长 ID 数字字符串,应具有字符串/对象类型。但即使我确保 pandas 将所有列解析为object

df = pd.read_csv('data.csv', dtype=object)
print(df.dtypes)  # sanity check
df.to_hdf('df.h5', 'df')

> client_id                object
  event_id                 object
  account_id               object
  session_id               object
  event_timestamp          object
  # etc...

我收到此错误:

  File "foo.py", line 14, in <module>
    df.to_hdf('df.h5', 'df')
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/core/generic.py", line 1996, in to_hdf
    return pytables.to_hdf(path_or_buf, key, self, **kwargs)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/pytables.py", line 279, in to_hdf
    f(store)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/pytables.py", line 273, in <lambda>
    f = lambda store: store.put(key, value, **kwargs)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/pytables.py", line 890, in put
    self._write_to_group(key, value, append=append, **kwargs)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/pytables.py", line 1367, in _write_to_group
    s.write(obj=value, append=append, complib=complib, **kwargs)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/pytables.py", line 2963, in write
    self.write_array('block%d_values' % i, blk.values, items=blk_items)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/pytables.py", line 2730, in write_array
    vlarr.append(value)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/tables/vlarray.py", line 547, in append
    self._append(nparr, nobjects)
  File "tables/hdf5extension.pyx", line 2032, in tables.hdf5extension.VLArray._append
OverflowError: value too large to convert to int

显然它无论如何都试图将其转换为 int 并且失败了。

运行时df.to_feather()我有类似的问题:

df.to_feather('df.feather')
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/core/frame.py", line 1892, in to_feather
    to_feather(self, fname)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pandas/io/feather_format.py", line 83, in to_feather
    feather.write_dataframe(df, path)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pyarrow/feather.py", line 182, in write_feather
    writer.write(df)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pyarrow/feather.py", line 93, in write
    table = Table.from_pandas(df, preserve_index=False)
  File "pyarrow/table.pxi", line 1174, in pyarrow.lib.Table.from_pandas
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pyarrow/pandas_compat.py", line 501, in dataframe_to_arrays
    convert_fields))
  File "/usr/lib/python3.6/concurrent/futures/_base.py", line 586, in result_iterator
    yield fs.pop().result()
  File "/usr/lib/python3.6/concurrent/futures/_base.py", line 425, in result
    return self.__get_result()
  File "/usr/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pyarrow/pandas_compat.py", line 487, in convert_column
    raise e
  File "/shared_directory/projects/env/lib/python3.6/site-packages/pyarrow/pandas_compat.py", line 481, in convert_column
    result = pa.array(col, type=type_, from_pandas=True, safe=safe)
  File "pyarrow/array.pxi", line 191, in pyarrow.lib.array
  File "pyarrow/array.pxi", line 78, in pyarrow.lib._ndarray_to_array
  File "pyarrow/error.pxi", line 85, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: ('Could not convert 1542852887489 with type str: tried to convert to double', 'Conversion failed for column session_id with type object')

所以:

  1. 是否有任何看起来像数字的东西被强制转换为存储中的数字?
  2. NaN 的存在会影响这里发生的事情吗?
  3. 是否有替代存储解决方案?什么是最好的?
4

2 回答 2

7

在阅读了这个主题之后,似乎问题在于处理string-type 列。我的string列包含全数字字符串和带字符的字符串的混合。Pandas 可以灵活地选择将字符串保留为object,而无需声明类型,但在序列化hdf5feather列的内容转换为类型(strdouble,例如)时,不能混合。当遇到足够大的混合类型库时,这两个库都会失败。

将我的混合列强制转换为字符串允许我将其保存在羽毛中,但在 HDF5 中,文件膨胀并且当我用完磁盘空间时该过程结束。

是一个类似案例的答案,评论者指出(2 年前)“这个问题非常标准,但解决方案很少”。

一些背景:

Pandas 中的字符串类型称为object,但这掩盖了它们可能是纯字符串或混合 dtypes(numpy 具有内置的字符串类型,但 Pandas 从不将它们用于文本)。所以在这种情况下要做的第一件事就是将所有字符串 cols 强制为字符串类型(with df[col].astype(str))。但即便如此,在一个足够大的文件(16GB,长字符串)中,这仍然失败。为什么?

我遇到此错误的原因是我的数据具有高熵(许多不同的唯一值)字符串。(对于低熵数据,切换到 dtype 可能是值得的categorical。)在我的例子中,我意识到我只需要这些字符串来识别行 - 所以我可以用唯一的整数替换它们!

df[col] = df[col].map(dict(zip(df[col].unique(), range(df[col].nunique()))))

其他解决方案:

hdf5对于文本数据,除了/之外,还有其他推荐的解决方案feather,包括:

  • json
  • msgpack(请注意,在 Pandasread_msgpack中不推荐使用 0.25)
  • pickle(它有已知的安全问题,所以要小心 - 但它应该可以用于数据帧的内部存储/传输)
  • parquet,Apache Arrow 生态系统的一部分。

是 Matthew Rocklin(dask开发人员之一)比较msgpackpickle. 他在他的博客上写了一个更广泛的比较。

于 2019-07-21T13:43:30.893 回答
3

HDF5 不是此用例的合适解决方案。如果您有许多要存储在单个结构中的数据帧,hdf5 是一个更好的解决方案。打开文件时它有更多的开销,然后它允许您有效地加载每个数据帧并轻松加载它们的切片。它应该被认为是存储数据帧的文件系统。

在时间序列事件的单个数据帧的情况下,推荐的格式将是 Apache Arrow 项目格式之一,即featherparquet. 人们应该将它们视为基于列(压缩)的 csv 文件。这两者之间的特殊权衡在羽毛和镶木地板之间有什么区别?.

要考虑的一个特殊问题是数据类型。由于feather不是为通过压缩优化磁盘空间而设计的,因此它可以为更多种类的数据类型提供支持。虽然parquet试图提供非常有效的压缩,但它只能支持有限的子集,这将使其能够更好地处理数据压缩。

于 2019-07-27T19:56:13.623 回答