是否可以直接重命名存储在hdf5文件中的pandas dataframe的列?

时间:2015-08-18 18:18:26

标签: python-2.7 pandas hdf5

我有一个非常大的pandas数据帧存储在hdf5文件中,我需要重命名数据帧的列。

直接的方法是使用HDFStore.select以块的形式读取数据帧,重命名列并将块存储到另一个hdf5文件中。

但我认为这是一种愚蠢而低效的方式。有没有办法直接重命名hdf5文件中的列?

1 个答案:

答案 0 :(得分:3)

可以通过更改元数据来完成。大警告。这可能会损坏您的文件,因此您需要自担风险。

创建商店。必须是表格格式。我在这里没有使用data_columns,但重新命名的只是轻微的改变。

In [1]: df = DataFrame(np.random.randn(10,3),columns=list('abc'))

In [2]: df.to_hdf('test.h5','df',format='table')
In [24]: df.to_hdf('test.h5','df',format='table')

In [25]: pd.read_hdf('test.h5','df')
Out[25]: 
          a         b         c
0  1.366298  0.844646 -0.470735
1 -1.438387 -1.288432  0.250763
2 -1.290225 -0.390315 -0.138440
3  2.343019  0.632340 -0.539334
4 -1.184943  0.566479  1.977939
5 -1.530772  0.757110 -0.013930
6 -0.300345 -0.951563 -1.013957
7 -0.073975 -0.256521  1.024525
8 -0.179189 -1.767918  0.591720
9  0.641028  0.205522  1.947618

获取表格本身的句柄

In [26]: store = pd.HDFStore('test.h5')

您需要在2个位置更改元数据。首先是顶级

In [28]: store.get_storer('df').attrs['non_index_axes']
Out[28]: [(1, ['a', 'b', 'c'])]

In [29]: store.get_storer('df').attrs.non_index_axes = [(1, ['new','b','c'])]

然后在这里

In [31]: store.get_storer('df').table.attrs
Out[31]: 
/df/table._v_attrs (AttributeSet), 12 attributes:
   [CLASS := 'TABLE',
    FIELD_0_FILL := 0,
    FIELD_0_NAME := 'index',
    FIELD_1_FILL := 0.0,
    FIELD_1_NAME := 'values_block_0',
    NROWS := 10,
    TITLE := '',
    VERSION := '2.7',
    index_kind := 'integer',
    values_block_0_dtype := 'float64',
    values_block_0_kind := ['a', 'b', 'c'],
    values_block_0_meta := None]

In [33]: store.get_storer('df').table.attrs.values_block_0_kind = ['new','b','c']

关闭商店以保存

In [34]: store.close()

In [35]: pd.read_hdf('test.h5','df')
Out[35]: 
        new         b         c
0  1.366298  0.844646 -0.470735
1 -1.438387 -1.288432  0.250763
2 -1.290225 -0.390315 -0.138440
3  2.343019  0.632340 -0.539334
4 -1.184943  0.566479  1.977939
5 -1.530772  0.757110 -0.013930
6 -0.300345 -0.951563 -1.013957
7 -0.073975 -0.256521  1.024525
8 -0.179189 -1.767918  0.591720
9  0.641028  0.205522  1.947618
相关问题