将大熊猫df保存到hdf时发生OverflowError

Jos*_*der 9 python-3.x pandas hdf feather

我有一个大的Pandas数据框(〜15GB,8300万行),我有兴趣另存为h5(或feather)文件。一列包含数字的长ID字符串,该字符串应具有字符串/对象类型。但是即使我确保熊猫将所有列解析为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...
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

  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
Run Code Online (Sandbox Code Playgroud)

显然,它试图将其转换为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')
Run Code Online (Sandbox Code Playgroud)

所以:

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

Jos*_*der 7

对这个主题做了一些阅读后,问题似乎是处理string-type 列。我的string列包含全数字字符串和带字符的字符串的混合。Pandas 具有将字符串保持为 的灵活选项object,没有声明类型,但是当序列化为hdf5feather列的内容被转换为类型(str或者double,比如说)并且不能混合时。当遇到足够大的混合类型库时,这两个库都失败了。

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

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

一些背景:

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

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

df[col] = df[col].map(dict(zip(df[col].unique(), range(df[col].nunique()))))
Run Code Online (Sandbox Code Playgroud)

其他解决方案:

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

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

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