【发布时间】:2022-11-19 02:38:41
【问题描述】:
我有一个数据框,我想以可附加格式保存到 hdf5 文件中。数据框如下所示:
column1
0 [0, 1, 2, 3, 4]
复制该问题的代码是:
import pandas as pd
test = pd.DataFrame({"column1":[list(range(0,5))]})
test.to_hdf('test','testgroup',format="table")
不幸的是,它返回此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-65-c2dbeaca15df> in <module>
1 test = pd.DataFrame({"column1":[list(range(0,5))]})
----> 2 test.to_hdf('test','testgroup',format="table")
7 frames
/usr/local/lib/python3.7/dist-packages/pandas/io/pytables.py in _maybe_convert_for_string_atom(name, block, existing_col, min_itemsize, nan_rep, encoding, errors, columns)
4979 error_column_label = columns[i] if len(columns) > i else f"No.{i}"
4980 raise TypeError(
-> 4981 f"Cannot serialize the column [{error_column_label}]\n"
4982 f"because its data contents are not [string] but "
4983 f"[{inferred_type}] object dtype"
TypeError: Cannot serialize the column [column1]
because its data contents are not [string] but [mixed] object dtype
我知道我可以将每个值保存在单独的列中。这对我的扩展用例没有帮助,因为可能有可变长度的列表。
我知道我可以将列表转换为字符串,然后根据字符串重新创建它,但如果我开始将每一列转换为字符串,我还不如使用文本格式,如 csv,而不是二进制格式,如 hdf5。
是否有将列表保存为 hdf5 表格格式的标准方法?
【问题讨论】:
标签: python pandas dataframe hdf5 pytables