Python(pandas):使用多索引在hdf5中存储数据框

Dav*_*ide 5 python sql hdf5 multi-index pandas

我需要处理具有多索引的大尺寸数据框,所以我尝试创建一个数据框来学习如何将它存储在hdf5文件中.数据框如下:(前2列中的多索引)

Symbol    Date          0

C         2014-07-21    4792
B         2014-07-21    4492
A         2014-07-21    5681
B         2014-07-21    8310
A         2014-07-21    1197
C         2014-07-21    4722
          2014-07-21    7695
          2014-07-21    1774
Run Code Online (Sandbox Code Playgroud)

我正在使用pandas.to_hdf,但是当我尝试选择组中的数据时,它会创建一个"固定格式存储":

store.select('table','Symbol == "A"')
Run Code Online (Sandbox Code Playgroud)

它返回一些错误,主要问题是这个

TypeError: cannot pass a where specification when reading from a Fixed format store. this store must be selected in its entirety
Run Code Online (Sandbox Code Playgroud)

然后我试图像这样追加DataFrame:

store.append('ts1',timedata)
Run Code Online (Sandbox Code Playgroud)

这应该创建一个表,但这给了我另一个错误:

TypeError: [unicode] is not implemented as a table column
Run Code Online (Sandbox Code Playgroud)

所以我需要的代码将数据帧存储在一个表中HDF5格式并选择从单一索引的DATAS(为此目的,我发现这个代码:store.select('timedata','Symbol == "A"'))

Jef*_*eff 6

这是一个例子

In [8]: pd.__version__
Out[8]: '0.14.1'

In [9]: np.__version__
Out[9]: '1.8.1'

In [10]: import sys

In [11]: sys.version
Out[11]: '2.7.3 (default, Jan  7 2013, 09:17:50) \n[GCC 4.4.5]'

In [4]: df = DataFrame(np.arange(9).reshape(9,-1),index=pd.MultiIndex.from_product([list('abc'),date_range('20140721',periods=3)],names=['symbol','date']),columns=['value'])

In [5]: df
Out[5]: 
                   value
symbol date             
a      2014-07-21      0
       2014-07-22      1
       2014-07-23      2
b      2014-07-21      3
       2014-07-22      4
       2014-07-23      5
c      2014-07-21      6
       2014-07-22      7
       2014-07-23      8

In [6]: df.to_hdf('test.h5','df',mode='w',format='table')

In [7]: pd.read_hdf('test.h5','df',where='date=20140722')
Out[7]: 
                   value
symbol date             
a      2014-07-22      1
b      2014-07-22      4
c      2014-07-22      7

In [12]: pd.read_hdf('test.h5','df',where='symbol="a"')
Out[12]: 
                   value
symbol date             
a      2014-07-21      0
       2014-07-22      1
       2014-07-23      2
Run Code Online (Sandbox Code Playgroud)