【问题标题】:Converting from Excel to HDF5 using Pandas使用 Pandas 从 Excel 转换为 HDF5
【发布时间】:2017-01-11 00:19:14
【问题描述】:

我想将 Excel 文档的内容提取到 pandas 数据框,然后将该数据框写入 HDF5 文件。为此,我已经这样做了:

xls_df = pd.read_excel(fn_xls)
xls_df.to_hdf(fn_h5, 'table', format='table', mode='w')

这会导致以下错误:

TypeError:无法序列化列 [Col1],因为 它的数据内容是[unicode] object dtype

我尝试在 Excel 文件中的数据框上使用 convert.objects(),但这不起作用(并且 convert.objects() 已弃用)。对此有什么建议吗?

这里有一点关于 Excel 文件的信息:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 101 entries, 0 to 100
Data columns (total 5 columns):
Col1                   101 non-null object
Col2                   101 non-null object
Col3                   94 non-null float64
Col4                   98 non-null object
Col5                   93 non-null float64
dtypes: float64(2), object(3)

第一列和第二列是字符串,第四列有1个字符串但大部分是整数,第三列和第五列是整数。

【问题讨论】:

  • 显示数据框的一些示例条目?

标签: python excel pandas dataframe hdf5


【解决方案1】:

“Col4”列中的混合字符串和整数数据类型在转换为“table”格式的 HDF5 时会导致错误。

要以 hdf5“表格”格式保存,您需要将 Col4 中的数字转换为浮点数(并将字符串转换为 NaN):

df["Col4"] = pd.to_numeric(df["Col4"], errors="coerce")

或者将列中的所有内容都转换为字符串:

df["Col4"] = df["Col4"].astype(str)

或者使用允许列具有混合数据类型的“固定”hdf5 格式。这会将混合数据类型列保存为 python pickle 格式,并且当前会给出 PerformanceWarning。

df.to_hdf(outpath, 'yourkey', format='fixed', mode='w')

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2020-03-16
    • 2013-09-17
    • 2019-12-02
    • 2018-05-23
    • 2021-08-09
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多