Python存儲(chǔ)讀取HDF5文件代碼解析
HDF5 簡(jiǎn)介
HDF(Hierarchical Data Format)指一種為存儲(chǔ)和處理大容量科學(xué)數(shù)據(jù)設(shè)計(jì)的文件格式及相應(yīng)庫(kù)文件。HDF 最早由美國(guó)國(guó)家超級(jí)計(jì)算應(yīng)用中心 NCSA 開(kāi)發(fā),目前在非盈利組織 HDF 小組維護(hù)下繼續(xù)發(fā)展。當(dāng)前流行的版本是 HDF5。HDF5 擁有一系列的優(yōu)異特性,使其特別適合進(jìn)行大量科學(xué)數(shù)據(jù)的存儲(chǔ)和操作,如它支持非常多的數(shù)據(jù)類(lèi)型,靈活,通用,跨平臺(tái),可擴(kuò)展,高效的 I/O 性能,支持幾乎無(wú)限量(高達(dá) EB)的單文件存儲(chǔ)等,詳見(jiàn)其官方介紹:https://support.hdfgroup.org/HDF5/ 。
HDF5 結(jié)構(gòu)
HDF5 文件一般以 .h5 或者 .hdf5 作為后綴名,需要專門(mén)的軟件才能打開(kāi)預(yù)覽文件的內(nèi)容。HDF5 文件結(jié)構(gòu)中有 2 primary objects: Groups 和 Datasets。
Groups 就類(lèi)似于文件夾,每個(gè) HDF5 文件其實(shí)就是根目錄 (root) group'/',可以看成目錄的容器,其中可以包含一個(gè)或多個(gè) dataset 及其它的 group。
Datasets 類(lèi)似于 NumPy 中的數(shù)組 array,可以當(dāng)作數(shù)組的數(shù)據(jù)集合 。
每個(gè) dataset 可以分成兩部分: 原始數(shù)據(jù) (raw) data values 和 元數(shù)據(jù) metadata (a set of data that describes and gives information about other data => raw data)。
+-- Dataset
| +-- (Raw) Data Values (eg: a 4 x 5 x 6 matrix)
| +-- Metadata
| | +-- Dataspace (eg: Rank = 3, Dimensions = {4, 5, 6})
| | +-- Datatype (eg: Integer)
| | +-- Properties (eg: Chuncked, Compressed)
| | +-- Attributes (eg: attr1 = 32.4, attr2 = "hello", ...)
|
從上面的結(jié)構(gòu)中可以看出:
- Dataspace 給出原始數(shù)據(jù)的秩 (Rank) 和維度 (dimension)
- Datatype 給出數(shù)據(jù)類(lèi)型
- Properties 說(shuō)明該 dataset 的分塊儲(chǔ)存以及壓縮情況
- Chunked: Better access time for subsets; extendible
- Chunked & Compressed: Improves storage efficiency, transmission speed
- Attributes 為該 dataset 的其他自定義屬性
整個(gè) HDF5 文件的結(jié)構(gòu)如下所示:
+-- / | +-- group_1 | | +-- dataset_1_1 | | | +-- attribute_1_1_1 | | | +-- attribute_1_1_2 | | | +-- ... | | | | | +-- dataset_1_2 | | | +-- attribute_1_2_1 | | | +-- attribute_1_2_2 | | | +-- ... | | | | | +-- ... | | | +-- group_2 | | +-- dataset_2_1 | | | +-- attribute_2_1_1 | | | +-- attribute_2_1_2 | | | +-- ... | | | | | +-- dataset_2_2 | | | +-- attribute_2_2_1 | | | +-- attribute_2_2_2 | | | +-- ... | | | | | +-- ... | | | +-- ... |
一個(gè) HDF5 文件從一個(gè)命名為 "/" 的 group 開(kāi)始,所有的 dataset 和其它 group 都包含在此 group 下,當(dāng)操作 HDF5 文件時(shí),如果沒(méi)有顯式指定 group 的 dataset 都是默認(rèn)指 "/" 下的 dataset,另外類(lèi)似相對(duì)文件路徑的 group 名字都是相對(duì)于 "/" 的。
安裝
pip install h5py
Python讀寫(xiě)HDF5文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Created by WW on Jan. 26, 2020
# All rights reserved.
#
import h5py
import numpy as np
def main():
#===========================================================================
# Create a HDF5 file.
f = h5py.File("h5py_example.hdf5", "w") # mode = {'w', 'r', 'a'}
# Create two groups under root '/'.
g1 = f.create_group("bar1")
g2 = f.create_group("bar2")
# Create a dataset under root '/'.
d = f.create_dataset("dset", data=np.arange(16).reshape([4, 4]))
# Add two attributes to dataset 'dset'
d.attrs["myAttr1"] = [100, 200]
d.attrs["myAttr2"] = "Hello, world!"
# Create a group and a dataset under group "bar1".
c1 = g1.create_group("car1")
d1 = g1.create_dataset("dset1", data=np.arange(10))
# Create a group and a dataset under group "bar2".
c2 = g2.create_group("car2")
d2 = g2.create_dataset("dset2", data=np.arange(10))
# Save and exit the file.
f.close()
''' h5py_example.hdf5 file structure
+-- '/'
| +-- group "bar1"
| | +-- group "car1"
| | | +-- None
| | |
| | +-- dataset "dset1"
| |
| +-- group "bar2"
| | +-- group "car2"
| | | +-- None
| | |
| | +-- dataset "dset2"
| |
| +-- dataset "dset"
| | +-- attribute "myAttr1"
| | +-- attribute "myAttr2"
| |
|
'''
#===========================================================================
# Read HDF5 file.
f = h5py.File("h5py_example.hdf5", "r") # mode = {'w', 'r', 'a'}
# Print the keys of groups and datasets under '/'.
print(f.filename, ":")
print([key for key in f.keys()], "\n")
#===================================================
# Read dataset 'dset' under '/'.
d = f["dset"]
# Print the data of 'dset'.
print(d.name, ":")
print(d[:])
# Print the attributes of dataset 'dset'.
for key in d.attrs.keys():
print(key, ":", d.attrs[key])
print()
#===================================================
# Read group 'bar1'.
g = f["bar1"]
# Print the keys of groups and datasets under group 'bar1'.
print([key for key in g.keys()])
# Three methods to print the data of 'dset1'.
print(f["/bar1/dset1"][:]) # 1. absolute path
print(f["bar1"]["dset1"][:]) # 2. relative path: file[][]
print(g['dset1'][:]) # 3. relative path: group[]
# Delete a database.
# Notice: the mode should be 'a' when you read a file.
'''
del g["dset1"]
'''
# Save and exit the file
f.close()
if __name__ == "__main__":
main()
相關(guān)代碼示例
創(chuàng)建一個(gè)h5py文件
import h5py
f=h5py.File("myh5py.hdf5","w")
創(chuàng)建dataset
import h5py
f=h5py.File("myh5py.hdf5","w")
#deset1是數(shù)據(jù)集的name,(20,)代表數(shù)據(jù)集的shape,i代表的是數(shù)據(jù)集的元素類(lèi)型
d1=f.create_dataset("dset1", (20,), 'i')
for key in f.keys():
print(key)
print(f[key].name)
print(f[key].shape)
print(f[key].value)
輸出:
dset1
/dset1
(20,)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
賦值
import h5py
import numpy as np
f=h5py.File("myh5py.hdf5","w")
d1=f.create_dataset("dset1",(20,),'i')
#賦值
d1[...]=np.arange(20)
#或者我們可以直接按照下面的方式創(chuàng)建數(shù)據(jù)集并賦值
f["dset2"]=np.arange(15)
for key in f.keys():
print(f[key].name)
print(f[key].value)
輸出:
/dset1
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
/dset2
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
創(chuàng)建group
import h5py
import numpy as np
f=h5py.File("myh5py.hdf5","w")
#創(chuàng)建一個(gè)名字為bar的組
g1=f.create_group("bar")
#在bar這個(gè)組里面分別創(chuàng)建name為dset1,dset2的數(shù)據(jù)集并賦值。
g1["dset1"]=np.arange(10)
g1["dset2"]=np.arange(12).reshape((3,4))
for key in g1.keys():
print(g1[key].name)
print(g1[key].value)
輸出:
/bar/dset1
[0 1 2 3 4 5 6 7 8 9]
/bar/dset2
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
刪除某個(gè)key下的數(shù)據(jù)
# 刪除某個(gè)key,調(diào)用remove
f.remove("bar")
最后pandsa讀取HDF5格式文件
import pandas as pd
import numpy as np
# 將mode改成r即可
hdf5 = pd.HDFStore("hello.h5", mode="r")
# 或者
"""
hdfs = pd.read_hdf("hello.h5", key="xxx")
"""
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python簡(jiǎn)單實(shí)現(xiàn)的代理服務(wù)器端口映射功能示例
這篇文章主要介紹了Python簡(jiǎn)單實(shí)現(xiàn)的代理服務(wù)器端口映射功能,結(jié)合實(shí)例形式分析了Python模擬服務(wù)器、代理服務(wù)器及客戶端訪問(wèn)的相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
Python利用keras接口實(shí)現(xiàn)深度神經(jīng)網(wǎng)絡(luò)回歸
這篇文章主要為大家詳細(xì)介紹了基于Python語(yǔ)言中TensorFlow的Keras接口,實(shí)現(xiàn)深度神經(jīng)網(wǎng)絡(luò)回歸的方法。文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-02-02
Linux下python與C++使用dlib實(shí)現(xiàn)人臉檢測(cè)
這篇文章主要為大家詳細(xì)介紹了Linux下python與C++使用dlib實(shí)現(xiàn)人臉檢測(cè),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
python實(shí)現(xiàn)從wind導(dǎo)入數(shù)據(jù)
今天小編就為大家分享一篇python實(shí)現(xiàn)從wind導(dǎo)入數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
PyQt5 designer 頁(yè)面點(diǎn)擊按鈕跳轉(zhuǎn)頁(yè)面實(shí)現(xiàn)
本文主要介紹了PyQt5 designer 頁(yè)面點(diǎn)擊按鈕跳轉(zhuǎn)頁(yè)面實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
Python confluent kafka客戶端配置kerberos認(rèn)證流程詳解
這篇文章主要介紹了Python confluent kafka客戶端配置kerberos認(rèn)證流程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
python 應(yīng)用之Pycharm 新建模板默認(rèn)添加編碼格式-作者-時(shí)間等信息【推薦】
這篇文章主要介紹了Pycharm 新建模板默認(rèn)添加編碼格式-作者-時(shí)間等信息 ,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06
python開(kāi)發(fā)之thread實(shí)現(xiàn)布朗運(yùn)動(dòng)的方法
這篇文章主要介紹了python開(kāi)發(fā)之thread實(shí)現(xiàn)布朗運(yùn)動(dòng)的方法,實(shí)例分析了Python基于多線程實(shí)現(xiàn)繪圖的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
python 讀取文本文件的行數(shù)據(jù),文件.splitlines()的方法
今天小編就為大家分享一篇python 讀取文本文件的行數(shù)據(jù),文件.splitlines()的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07

