Pandas、多索引、日期、HDFstore 和frame_tables

标签 pandas

我想使用带有日期的多重索引作为分层索引类型之一。我还想将 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(putFixed格式存储,除非指定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/

相关文章:

python - 按跨年份的日历周分组

python - 在列值上绘制堆积条形图

python - Pandas 系列 any() 与 all()

python - 某些列的 Pandas 平均值

python - 更改行值,直到数据帧上出现特定行

python - Pandas 数据框中的编码/分解列表

python - 如何解决 Pandas 的导入错误?

python - 如何对 Pandas 数据框的选定列进行 Pearson 相关性

python - 将零值转换为 Pandas 中的空单元格

python - Xlsxwriter writer 正在编写自己的工作表并删除现有工作表