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

Posted

技术标签:

【中文标题】是否可以直接重命名存储在 hdf5 文件中的 pandas 数据框的列?【英文标题】:Is it possible to directly rename pandas dataframe's columns stored in hdf5 file? 【发布时间】:2015-11-11 19:56:05 【问题描述】:

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

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

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

【问题讨论】:

【参考方案1】:

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

创建商店。必须是表格格式。我没有在这里使用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

【讨论】:

这可以是 Pandas 的功能请求吗? 当然。似乎有道理。如果你愿意,请发布一个问题。

以上是关于是否可以直接重命名存储在 hdf5 文件中的 pandas 数据框的列?的主要内容,如果未能解决你的问题,请参考以下文章

为大型 hdf5 文件重命名组中的所有 HDF5 数据集时出现问题

在 Databricks 文件系统中更改文件夹名称

如何在 S3 上重命名存储桶中的文件夹?

Amazon S3 boto:如何重命名存储桶中的文件?

搜索 HDF5 数据集

使用 Pandas 从查找字典中重命名多索引行