【发布时间】:2020-08-04 14:04:01
【问题描述】:
我正在尝试将 pandas DataFrame 导出到 hdf5 文件。具有以下结构的 DataFrame。
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 a 4 non-null float64
1 b 4 non-null float64
2 c 4 non-null float64
3 d 4 non-null object
dtypes: float64(3), object(1)
memory usage: 256.0+ bytes
在 d 列中,我确实将一些文件路径存储为类型。
<class 'pathlib.WindowsPath'>
如果我这样调用 to_hdf() 函数
df.to_hdf(r'C:\data\test.h5', mode='w', key=key,format='table', data_columns=True)
我会收到以下错误。
File "C:\py36_4\lib\site-packages\pandas\io\pytables.py", line 4800, in _maybe_convert_for_string_atom
for i in range(len(block.shape[0])):
TypeError: object of type 'int' has no len()
如果我跳过 d 列,导出到 hdf5 将按预期工作。因此,这似乎是 d 列和使用的类型 '<class 'pathlib.WindowsPath'>' 的问题?
更新我的问题:
以下代码将重现此问题。
df1=pd.DataFrame({'a':['test1','test2'],'b':[1.1,2.1]})
df1.to_hdf('test1.h5', key='test1', format='table', data_columns=True)
df2=pd.DataFrame(df1.loc[1,:]).transpose()
df2.to_hdf('test2.h5', key='test2', format='table', data_columns=True)
我看起来问题来自 transpose() 函数。这会将所有列的dtype 更改为object,并且df2 的hdf5 导出将失败。这似乎也只有在 DataFrame df1 的一列属于这种类型时才会发生。
【问题讨论】:
-
我做了一些进一步的测试。如果我将 d 列转换为字符串,则导出正在工作。 df.d=df.d.astype(str)。所以在 hdf5 导出中不支持
类型。
标签: python pandas hdf5 pathlib