有很多关于如何将csv文件读入pandas dataframe的信息,但我手头有一个pyTable表格,想要转换成pandas DataFrame。
我已经找到了如何将我的pandas DataFrame存储到pytables中...现在我想要读取它,此时它应该是:
"kind = v._v_attrs.pandas_type"
我可以把它写成csv文件再重新读入,但这似乎很愚蠢,目前就是这么做的。
我应该如何将pytable对象读入pandas?
import tables as pt
import pandas as pd
import numpy as np
# the content is junk but we don't care
grades = np.empty((10,2), dtype=(('name', 'S20'), ('grade', 'u2')))
# write to a PyTables table
handle = pt.openFile('/tmp/test_pandas.h5', 'w')
handle.createTable('/', 'grades', grades)
print handle.root.grades[:].dtype # it is a structured array
# load back as a DataFrame and check types
df = pd.DataFrame.from_records(handle.root.grades[:])
df.dtypes
请注意,您的u2(无符号2字节整数)将会变成i8(8字节整数),并且字符串将被视为对象,因为Pandas尚未支持Numpy数组可用的所有dtype范围。
现在文档中包括一个关于使用HDF5存储的优秀部分,并且在食谱中讨论了一些更高级的策略。
现在相对来说比较简单:
In [1]: store = HDFStore('store.h5')
In [2]: print store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
Empty
In [3]: df = DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
In [4]: store['df'] = df
In [5]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame (shape->[2,2])
并从HDF5/pytables检索:
In [6]: store['df'] # store.get('df') is an equivalent
Out[6]:
A B
0 1 2
1 3 4
您还可以在表格内查询。
[]
)来分组dtype规范,而不是元组(()
)。 - meteore