转载 Python 存储与读取HDF5文件
HDF5 简介
HDF(Hierarchical Data Format)指一种为存储和处理大容量科学数据设计的文件格式及相应库文件。HDF 最早由美国国家超级计算应用中心 NCSA 开发,目前在非盈利组织 HDF 小组维护下继续发展。当前流行的版本是 HDF5。HDF5 拥有一系列的优异特性,使其特别适合进行大量科学数据的存储和操作,如它支持非常多的数据类型,灵活,通用,跨平台,可扩展,高效的 I/O 性能,支持几乎无限量(高达 EB)的单文件存储等,详见其官方介绍:https://support.hdfgroup.org/HDF5/ 。
HDF5 结构
HDF5 文件一般以 .h5 或者 .hdf5 作为后缀名,需要专门的软件才能打开预览文件的内容。HDF5 文件结构中有 2 primary objects: Groups 和 Datasets。
- Groups 就类似于文件夹,每个 HDF5 文件其实就是根目录 (root) group
'/',可以看成目录的容器,其中可以包含一个或多个 dataset 及其它的 group
。 - Datasets 类似于 NumPy 中的数组 array,可以当作数组的数据集合 。
每个 dataset 可以分成两部分: 原始数据 (raw) data values 和 元数据 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", ...)
|
从上面的结构中可以看出:
- Dataspace 给出原始数据的秩 (Rank) 和维度 (dimension)
- Datatype 给出数据类型
- Properties 说明该 dataset 的分块储存以及压缩情况
- Chunked: Better access time for subsets; extendible
- Chunked & Compressed: Improves storage efficiency, transmission speed
- Attributes 为该 dataset 的其他自定义属性
整个 HDF5 文件的结构如下所示:

+-- /
| +-- 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
| | | +-- ...
| | |
| | +-- ...
| |
| +-- ...
|

pip install h5py
Python读写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()

相关代码示例
创建一个h5py文件
import h5py
f=h5py.File("myh5py.hdf5","w")
创建dataset

import h5py
f=h5py.File("myh5py.hdf5","w")
#deset1是数据集的name,(20,)代表数据集的shape,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)
#或者我们可以直接按照下面的方式创建数据集并赋值
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]

创建group

import h5py
import numpy as np
f=h5py.File("myh5py.hdf5","w") #创建一个名字为bar的组
g1=f.create_group("bar") #在bar这个组里面分别创建name为dset1,dset2的数据集并赋值。
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]]

删除某个key下的数据
# 删除某个key,调用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")
"""

转载 Python 存储与读取HDF5文件的更多相关文章
- 深入学习python解析并读取PDF文件内容的方法
这篇文章主要学习了python解析并读取PDF文件内容的方法,包括对学习库的应用,python2.7和python3.6中python解析PDF文件内容库的更新,包括对pdfminer库的详细解释和应 ...
- Windows下使用Fortran读取HDF5文件
需要用Fortran读取HDF5格式的GPM IMERG卫星降水文件,在已经安装HDF5库(参见VS2019+ Intel Fortran (oneAPI)+HDF5库的安装+测试 - chinago ...
- [转] C#实现在Sql Server中存储和读取Word文件 (Not Correct Modified)
出处 C#实现在Sql Server中存储和读取Word文件 要实现在Sql Server中实现将文件读写Word文件,需要在要存取的表中添加Image类型的列,示例表结构为: CREATE TABL ...
- python使用h5py读取mat文件数据,并保存图像
1 安装h5py sudo apt-get install libhdf5-dev sudo pip install h5py 假设你已经安装好python和numpy模块 2 读取mat文件数据 i ...
- python利用xlrd读取excel文件始终报错原因
1.代码按照网上百度的格式进行书写如下: 但运行后,始终报错如下: 百度了xlrd网页: 分明支持xls和xlsx两种格式的文件,但运行始终报错. 最后找到原因是因为我所读取的文件虽然是以.xls命名 ...
- python 使用read_csv读取 CSV 文件时报错
读取csv文件时报错 df = pd.read_csv('c:/Users/NUC/Desktop/成绩.csv' ) Traceback (most recent call last): File ...
- Python 存储数据到json文件
1 前言 很多程序都要求用户输入某种信息,程序一般将信息存储在列表和字典等数据结构中. 用户关闭程序时,就需要将信息进行保存,一种简单的方式是使用模块json来存储数据. 模块json让你能够将简单的 ...
- python 作业 批量读取excel文件并合并为一张excel
1 #!/usr/bin/env python 2 # coding: utf-8 3 4 def concat_file(a,b): 5 #如何批量读取并快速合并文件夹中的excel文件 6 imp ...
- Python基础之读取ini文件
基本使用方法 第一步:准备一份INI文件.如test1.ini [ITEMS] item1=1 item2=2 item3=3 item4=4 [ITEM1] test1=aaa [ITEM2] te ...
- 用python的pandas读取excel文件中的数据
一.读取Excel文件 使用pandas的read_excel()方法,可通过文件路径直接读取.注意到,在一个excel文件中有多个sheet,因此,对excel文件的读取实际上是读取指定文件.并 ...
随机推荐
- 封神台 SQL注入 靶场 (猫舍)手动注入
封神台 SQL注入 靶场 (猫舍)手动注入 靶场地址 http://pu2lh35s.ia.aqlab.cn/?id=1 使用脚本 可以直接使用sqlmap脚本 直接 对这个地址进行测试 不过这样实在 ...
- 小集训 CSP-S 模拟赛
DAY 1 A.喜剧的迷人之处在于 小思维题不必细讲 B. 镜中的野兽 状压+容斥 $ gcd (x) + lcm(x) = m $ ,可以得知 $ gcd(x) $ 一定是 m 的因子,那么就可以枚 ...
- Cloth Simulation with Root Finding and Optimization
目录 0 前言 1 Implicit Method 1.1 Root-finding 1.2 Optimization 1.3 Insight 2 Newton-Raphson Method 3 Ma ...
- C语言之输入输出
标准库 IO 输入输出功能并非C语言的组成部分,ANSI标准定义了相关的库函数 输入输出 <stdio.h> 流stream是与设备关联的数据的源或者目的地. 文本流:由文本行组成的序列 ...
- [python]多线程快速入门
前言 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.由于CPython的GIL限制,多线程实际为单线程,大多只用来处理IO密集型任务. Python一般用标准库 ...
- 《Selenium自动化测试实战:基于Python》之 基于Docker与Selenium Grid的测试技术
基于Docker与Selenium Grid的测试技术 10.1 Selenium Grid简介 尽管即将推出的Selenium 4.0对Seleni ...
- CUDA编程学习 (1)——CUDA C介绍
1. 内存分配和数据移动 API 函数 CUDA编程模型是一个异构模型,需要CPU和GPU协同工作.在CUDA中,host 和 devic e 是两个重要的概念,我们用host指代CPU及其内存,而用 ...
- 一文彻底弄懂JUC工具包的Semaphore
Semaphore 是 Java 并发包 (java.util.concurrent) 中的重要工具,主要用于控制多线程对共享资源的并发访问量.它可以设置"许可证"(permit) ...
- 移动端元素定位辅助神器-WEditor
WEditor可以做什么? 编辑器能够提供辅助编写脚本,查看组件信息,调试代码等功能. 移动端除了用 Appium 来 做元素定位外,还可以通过 WEditor 来完成. 前置环境依赖按照 以 win ...
- 如何使用Flask编写一个网站
使用Flask编写一个网站是一个相对简单且有趣的过程.Flask是一个用Python编写的轻量级Web应用框架.它易于上手,同时也非常强大,适合构建从简单的博客到复杂的Web应用的各种项目.以下是一个 ...