【发布时间】:2015-08-17 05:28:15
【问题描述】:
我正在尝试使用 pandas 内置函数 to_hdf 将 DataFrame 保存到 HDF5 存储中 但这会引发以下异常:
文件“C:\python\lib\site-packages\pandas\io\pytables.py”,第 3433 行,在 > >create_axes 提高e TypeError:无法序列化列 [日期] 因为 它的数据内容是[datetime] object dtype
数据框是从一个 numpy 数组构建的,每列都有正确的类型
我尝试在其他帧中读取时转换_object(),但仍然失败
这是我的测试代码,我显然在数据转换方面遗漏了一些东西,但不知道是什么
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
columns = ['date', 'c1', 'c2']
# building a sample test numpy array with datetime, float and integer
dtype = np.dtype("datetime64, f8, i2")
np_data = np.empty((0, len(columns)), dtype=dtype)
for i in range(1, 3):
line = [datetime(2015, 1, 1, 12, i), i/2, i*1000]
np_data = np.append(np_data, np.array([line]), axis=0)
print('##### the numpy array')
print(np_data)
# creating DataFrame from numpy array
df = pd.DataFrame(np_data, columns=columns)
# trying to force object conversion
df.convert_objects()
print('##### the DataFrame array')
print(df)
# the following fails!
try:
df.to_hdf('store.h5', 'data', append=True)
print('worked')
except Exception, e:
print('##### the error')
print(e)
上面的代码产生以下输出
##### the numpy array
[[datetime.datetime(2015, 1, 1, 12, 1) 0 1000]
[datetime.datetime(2015, 1, 1, 12, 2) 1 2000]]
##### the DataFrame array
date c1 c2
0 2015-01-01 12:01:00 0 1000
1 2015-01-01 12:02:00 1 2000
##### the error
Cannot serialize the column [date] because
its data contents are [datetime] object dtype
【问题讨论】:
标签: python python-2.7 datetime pandas hdf5