python ( Pandas ): store a data frame in hdf5 with a multi index

标签 python sql pandas hdf5 multi-index

我需要使用具有多索引的大维度数据框,所以我尝试创建一个数据框来学习如何将它存储在 hdf5 文件中。 数据框是这样的:(前两列有多索引)

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

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

store.select('table','Symbol == "A"')

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

TypeError: cannot pass a where specification when reading from a Fixed format store. this store must be selected in its entirety

然后我尝试像这样附加 DataFrame:

store.append('ts1',timedata)

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

TypeError: [unicode] is not implemented as a table column

所以我需要代码以 hdf5 格式将数据框存储在表中并从单个索引中选择数据(为此我找到了这段代码:store.select('timedata','Symbol == "A"') )

最佳答案

举个例子

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

关于 python ( Pandas ): store a data frame in hdf5 with a multi index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24892904/

相关文章:

python - NS3 - python.h 文件无法定位编译错误

python - 在 ListView 上测试 get_context_data() 会抛出 'AttributeError: object has no attribute ' object_list'

python - 将训练数据更改为 libsvm 格式以将其传递给 libsvm 中的 grid.py

java - JSP 数据库访问不工作

MySQL 避免在 CurrentTimeStamp 中重复条目

python - 将时间序列数据集中的随机值设为零

python - 如何用 Pandas 中的单个句点和问号替换 '..' 和 '?.'? df ['column' ].str.replace 不起作用

python - PNG 支持 python 3.3

sql - 检查一个值是否可以在 postgres 中被类型化为一个间隔

python - 使用集合创建列会复制集合 n 次