【问题标题】:How to merge a `pandas` DataFrame and a `numpy` array into H5如何将 `pandas` DataFrame 和 `numpy` 数组合并到 H5 中
【发布时间】:2019-08-31 03:37:47
【问题描述】:

我希望生成一个 H5 文件 file.h5,其中包含 pandas DataFrame 和 numpy 数组。

举例来说,假设我们将数组 array 和 DataFrame df 定义为:

import numpy as np
import pandas as pd

array = np.array([0,1])
data  = {'col': [2,3, 4]}
df = pd.DataFrame.from_dict(data)

我可以使用以下方法输出数组和 DataFrame 以分隔 H5 文件:

import h5py

f = h5py.File('array.h5', 'w')
f.create_dataset(name='my_array',
                 shape=array.shape,
                 dtype=array.dtype,
                 data=array)

df.to_hdf('dataframe.h5')

问题

  1. 如何将array.h5dataframe.h5 合并到file.h5
  2. 如何将arraydf 合并为可输出为H5 格式的结构?

【问题讨论】:

  • 您可以将数组添加为新列,然后写入.h5 文件:df['array'] = pd.Series(array)
  • h5py 写入和读取 numpy 数组。 df.to_hdf 使用(我认为)pytables 和某种 Store 模块。我自己并没有太多地使用它,但我认为df 存储可以使用h5py 读取,尽管它是一个复杂的group,使用df.values 和行/列索引数组。
  • 您应该能够对文件执行to_hdf,然后使用附加模式使用h5py 打开文件。然后编写数组数据集。但我对熊猫hdf 的了解还不够,不知道负载会如何。另一个想法是将数组放入 pandas Series(如果是 1d)并保存。
  • 在查看 dataframe.h5h5py(或 h5dump)时可能值得您了解它使用的组/数据集布局。
  • 最终目标是拥有一个具有各种numpy 张量和DataFrames 包含相应元数据的H5,这就是为什么我不能将数组添加到数据帧的原因。

标签: python pandas h5py


【解决方案1】:

不完全是你想要的。我不知道这是否可能。但是您可以在同一个文件中写入数组、数据框。但它正在丢失数据框的列索引名称。

import numpy as np
import pandas as pd
import h5py

np_array = np.array([0, 1])
data = {'col': [2, 3, 4], 'col2': [1, 2, 3]}
df = pd.DataFrame.from_dict(data)

with h5py.File("my_test_file.h5", 'w') as hf:
    hf.create_dataset("numpy_db", data=np_array)
    hf.create_dataset("pd_db", data=df)

with h5py.File('my_test_file.h5', 'r') as hf:
    np_db = hf['numpy_db'][:]
    pd_db = hf['pd_db'][:]
### But you will loose the column index name
pd_db = pd.DataFrame(pd_db)
np_db

【讨论】:

  • h5py 保存一个数组。如果给定一个数据框,它将首先将其转换为数组。我认为这相当于保存df.valuesdf.to_numpy()。如果数据框只有数值,那应该可以正常工作,但任何列 dtype 是 object(例如字符串),它可能会失败。
【解决方案2】:
In [134]: array = np.array([0,1]) 
     ...: data  = {'col': [2,3, 4]} 
     ...: df = pd.DataFrame.from_dict(data)                                                                  
In [135]: import h5py                                                                                        
In [136]: df                                                                                                 
Out[136]: 
   col
0    2
1    3
2    4

In [138]: sf = pd.Series(array)                                                                              
In [139]: sf                                                                                                 
Out[139]: 
0    0
1    1
dtype: int64

将 pandas 对象写入文件:

In [141]: df.to_hdf('dataframe.h5',key='df')                                                                 
In [142]: sf.to_hdf('dataframe.h5',key='sf',mode='a')

h5py打开文件:

In [144]: f = h5py.File('dataframe.h5', 'a')                                                                 
In [145]: list(f.keys())                                                                                     
Out[145]: ['df', 'sf']
In [146]: list(f['df'].keys())                                                                               
Out[146]: ['axis0', 'axis1', 'block0_items', 'block0_values']
In [147]: list(f['sf'].keys())                                                                               
Out[147]: ['index', 'values']
In [148]: f['sf/values'][:]                                                                                  
Out[148]: array([0, 1])           # the series is easy to read

将数组写入数据集:

In [149]: f.create_dataset(name='myarray',data=array)                                                        
Out[149]: <HDF5 dataset "myarray": shape (2,), type "<i8">
In [150]: list(f.keys())                                                                                     
Out[150]: ['df', 'myarray', 'sf']
In [151]: f.close()     

我可以阅读两个熊猫组:

In [154]: pd.read_hdf('dataframe.h5', key='df')                                                              
Out[154]: 
   col
0    2
1    3
2    4
In [155]: pd.read_hdf('dataframe.h5', key='sf')                                                              
Out[155]: 
0    0
1    1
dtype: int64

pd.read_hdf 无法处理 myarray

在 shell 中,我可以使用 h5dump

查看文件
1230:~/mypy$ h5ls dataframe.h5
df                       Group
myarray                  Dataset {2}
sf                       Group

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 2021-08-03
    • 2019-03-12
    • 2017-08-25
    • 2019-08-04
    • 2020-02-10
    • 2018-12-27
    • 2021-01-16
    相关资源
    最近更新 更多