我想使用带有日期的多重索引作为分层索引类型之一。我还想将 DataFrame 保存为frame_table,以便我可以从磁盘中选择子集,而无需加载整个内容。我目前收到一个错误:TypeError: [date] is not returned as a table columns
我想知道我是否错误地使用了多重索引,或者这确实是 Pandas 的限制。谢谢!
import pandas as pd, numpy, datetime
print pd.__version__ #-> 0.13.0rc1
idx1 = pd.MultiIndex.from_tuples([(datetime.date(2013,12,d), s, t) for d in range(1,3) for s in range(2) for t in range(3)])
df1 = pd.DataFrame(data=numpy.zeros((len(idx1),2)), columns=['a','b'], index=idx1)
with pd.get_store('test1.h5') as f:
f.put('trials',df1) #-> OK
with pd.get_store('test2.h5') as f:
f.put('trials',df1,data_colums=True,format='t') #-> TypeError: [date] is not implemented as a table column
最佳答案
使用datetime.datetime
,因为这些类型可以有效存储。文件是here有关在 HDFStore
中存储多索引帧的示例。
存储多索引时,您必须指定级别名称(如果您尝试将其存储在 ATM 上,HDFStore
目前不会警告您;这个问题将在下一版本中解决)。
In [20]: idx1 = pd.MultiIndex.from_tuples([(datetime.datetime(2013,12,d), s, t) for d in range(1,3) for s in range(2) for t in range(3)],names=['date','s','t'])
In [21]: df1 = pd.DataFrame(data=numpy.zeros((len(idx1),2)), columns=['a','b'], index=idx1)
您需要存储为table
(put
以Fixed
格式存储,除非指定append
) .
In [22]: df1.to_hdf('test.h5','df',mode='w',format='table')
In [23]: pd.read_hdf('test.h5','df')
Out[23]:
a b
date s t
2013-12-01 0 0 0 0
1 0 0
2 0 0
1 0 0 0
1 0 0
2 0 0
2013-12-02 0 0 0 0
1 0 0
2 0 0
1 0 0 0
1 0 0
2 0 0
[12 rows x 2 columns]
样本选择
In [8]: pd.read_hdf('test.h5','df',where='date=20131202')
Out[8]:
a b
date s t
2013-12-02 0 0 0 0
1 0 0
2 0 0
1 0 0 0
1 0 0
2 0 0
[6 rows x 2 columns]
关于Pandas、多索引、日期、HDFstore 和frame_tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340538/