Формат h5 чем открыть питон
If you’re storing large amounts of data that you need to quick access to, your standard text file isn’t going to cut it. The kinds of cosmological simulations that I run generate huge amounts of data, and to analyse them I need to be able access the exact data that I want quickly and painlessly.
HDF5 is one answer. It’s a powerful binary data format with no upper limit on the file size. It provides parallel IO, and carries out a bunch of low level optimisations under the hood to make queries faster and storage requirements smaller.
Here’s a quick intro to the h5py package, which provides a Python interface to the HDF5 data format. We’ll create a HDF5 file, query it, create a group and save compressed data.
You’ll need HDF5 installed, which can be a pain. Getting h5py is relatively painless in comparison, just use your favourite package manager.
Creating HDF5 files
We first load the numpy and h5py modules.
Now mock up some simple dummy data to save to our file.
The first step to creating a HDF5 file is to initialise it. It uses a very similar syntax to initialising a typical text file in numpy. The first argument provides the filename and location, the second the mode. We’re writing the file, so we provide a w for write access.
This creates a file object, hf , which has a bunch of associated methods. One is create_dataset , which does what it says on the tin. Just provide a name for the dataset, and the numpy array.
All we need to do now is close the file, which will write all of our work to disk.
Reading HDF5 files
To open and read data we use the same File method in read mode, r.
To see what data is in this file, we can call the keys() method on the file object.
We can then grab each dataset we created above using the get method, specifying the name.
This returns a HDF5 dataset object. To convert this to an array, just call numpy’s array method.
Groups
Groups are the basic container mechanism in a HDF5 file, allowing hierarchical organisation of the data. Groups are created similarly to datasets, and datsets are then added using the group object.
We can also create subfolders. Just specify the group name as a directory format.
As before, to read data in irectories and subdirectories use the get method with the full subdirectory path.
Python(x, y) — набор библиотек и программного обеспечения для численных расчетов, анализа и визуализации данных на основе Python. IDE представлены IDLE, Eclipse и Spyder, основой GUI избран Qt. Я расскажу вкратце о модулях, относящихся к самому Python, приведу несколько примеров их работы. Во время установки можно выбрать только то, что нужно, поэтому стоит разобраться что к этому нужному отнести. Кроме того, рассказ о модулях может пригодиться и сам по себе, поскольку их можно установить и по отдельности. Порядок следования модулей повторяет порядок оригинальной страницы и список чекбоксов установки.
Python — стандартные библиотеки, сейчас используется Python 2.6.5
Spyder (Scientific PYthon Development EnviRonment) — IDE для интерактивных вычислений и визуализации данных, документация
formlayout — создание форм диалогов/виджетов для редактирования каких-то вводимых параметров без написания GUI-кода. Например:
Copy Source | Copy HTML
from formlayout import fedit
datalist = [( 'Name' , 'Paul' ),
( 'Age' , 30 ),
( 'Sex' , [ 0 , 'Male' , 'Female' ]),
( 'Size' , 12 . 1 ),
( 'Eyes' , 'green' ),
( 'Married' , True),
]
print "result:" , fedit(datalist, title= "Describe yourself" ,
comment= "This is just an example." )
PyQwt — привязка Python к библиотеке Qwt для построения двумерной графики на Qt, примеры
wxPython — альтернативная GUI библиотека. Хотя очевидно, что здесь всюду продвигается PyQt, она нужна для популярного набора программ ETS, а также отладчика winpdb
NumPy — популярный модуль для высокоэффективной работы с многомерными массивами (ядро модуля SciPy), краткое введение в NumPy
SciPy — содержит модули для математической оптимизации, интегрирования, специальных функций, обработки сигналов, обработки изображений, генетических алгоритмов, решения обыкновенных дифференциальных уравнений и многих других задач
numexpr — быстрое вычисление выражений для элементов массивов с помощью векторной виртуальной машины. Например:
Copy Source | Copy HTML
>>> import numpy as np
>>> import numexpr as ne
>>> a = np.arange( 10 )
>>> a
array([ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ])
>>> b = np.arange( 0 , 20 , 2 )
>>> b
array([ 0 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18 ])
>>> c = ne.evaluate( "2*a+3*b" )
>>> c
array([ 0 , 8 , 16 , 24 , 32 , 40 , 48 , 56 , 64 , 72 ])
guidata — автоматическое создание GUI для удобного ввода данных и их показа, простейший из примеров:
Что здесь происходит? В точности то, что делал бы я в отсутствии мыши, для того, чтобы получить тот же результат, который получится. Я нажал бы левую клавишу windows , то есть зашел в меню «Пуск» своего Windows XP, потом три раза клавишу «вверх» , так я перешел к «Выполнить. », нажал бы клавишу , набрал notepad и запустил так блокнот, написал в нем типичное HelloWorld, закрыл с помощью alt-f4, что записывается как %, появился типичный диалог о сохранении данных «Да Нет Отмена», нажал клавишу , чтобы выбрать «Нет» и . Паузы нужны, чтобы успели открыться необходимые программы и ввестись соответствующие символы.
Одновременно с исполнением этого кода не стоит стоять под деревом что-то делать, поскольку активное окно переключится и нарушится последовательность команд. Тогда, к слову, в моем примере может произойти и компьютер выключится. Конечно, этот модуль можно использовать и более разумно, для того же упрощения обычной обработки событий.
pywinauto — набор модулей для автоматизации Microsoft Windows GUI (действия мыши и клавиатуры)
pyvisa — контроль всех видов измерительных устройств с помощью различных шин (GPIB, RS232, USB)
PyParallel — библиотека доступа к параллельному порту
PySerial — библиотека доступа к последовательному порту
Cython — язык, основанный на Python, позволяющий более плотно использовать скоростные возможности С
psyco — модуль, позволяющий повысить скорость выполнения кода на Python, причем во многих случаях достаточно лишь перед основным кодом добавить всего две строчки (или чуть больше, если обернуть их в try-except ImportError):
Python понимает все популярные форматы файлов. Кроме того, у каждой библиотеки есть свой, «теплый ламповый», формат. Синтаксис, разумеется, у каждого формата сугубо индивидуален. Я собрал все функции для работы с файлами разных форматов на один лист A4, с приложением в виде примера использования в jupyter notebook.
Я условно разделил форматы на три блока по способу использования. Как известно, файлы нужны для обмена информацией: между людьми, между программами (первый блок), между компьютером и сетью (второй) и «save game» – между одной и той же программой в разные моменты времени (третий блок).
Вкратце о каждом блоке:
1) Универсальные форматы:
- .csv – текстовый, значения, разделённые по идее запятыми (comma separated), но например, русский эксель предпочитает разделять точками с запятыми, поскольку в русской локали запятая уже используется – в качестве десятичного разделителя;
- .raw – бинарный формат для тех, кто не любит форматы файлов. Тип данных и, если данные многомерные, соответствующие размеры должны передаваться отдельно, в файле только сами данные;
- .xls/.xlsx – старый бинарный (ограничение в 65k строк) и новый xml’ный форматы экселя;
- .mat – это на самом деле тоже два формата (оба бинарные): старый проприетарный и новый на основе hdf5. Питон умеет работать с обоими (через библиотеки).
- .json – текстовый, выглядит как словарь в питоне, но кавычки можно использовать только двойные;
- .xml – текстовый, похож на html.
- .pkl – бинарный формат, в него умеют сохраняться все встроенные питоновские объекты. Пользовательские классы тоже умеют, а если питон сохраняет как-то не так, можно ему помочь через магические методы. Поддерживает дописывание в конец существующего файла (appending).
- .npy и .npz – в numpy аж целых два своих формата (оба бинарные). Появились как реакция на потерю обратной совместимости у pkl в момент перехода python v2->v3. Накладные расходы минимальные (~ на 100 байт больше, чем соответствующий raw; pkl, впрочем, немногим больше: на ~150 байт больше raw). В .npy можно сохранить только один массив, а в npz – сразу несколько, причём достать их оттуда впоследствии можно по имени.
- .h5 – бинарный формат hdf5. Примечателен тем, что в нем можно хранить целую иерархическую структуру данных, это практически файловая система в одном файле. Кроме того, его можно открыть в matlab без конвертации. Минусы:
a) небольшие файлы занимают неоправданно много места (например, 300 байт pkl vs 3.1 Мb у h5),
b) много багов,
c) есть дописывание в существующий файл, но если при этом случится ошибка (а так бывает), данные из него достать будет проблематично.
– в формате pdf
– в формате png:
Пример использования всех функций с диаграммы: html с оглавлением и ipynb-исходником
I am trying to read data from hdf5 file in Python. I can read the hdf5 file using h5py , but I cannot figure out how to access data within the file.
My code
This works and the file is read. But how can I access data inside the file object f1 ?
Is an hdf5 file different from an hdf file? I have hdf s (they are several bands of images), but I cannot figure out how to open them.
10 Answers 10
Read HDF5
Write HDF5
See h5py docs for more information.
Alternatives
- JSON: Nice for writing human-readable data; VERY commonly used (read & write)
- CSV: Super simple format (read & write)
- pickle: A Python serialization format (read & write) (Python package): More compact representation (read & write) (Python package): Nice for matrices (read & write)
- XML: exists too *sigh* (read & write)
For your application, the following might be important:
- Support by other programming languages
- Reading / writing performance
- Compactness (file size)
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
As of h5py version 2.1: "The property Dataset.value , which dates back to h5py 1.0, is deprecated and will be removed in a later release. This property dumps the entire dataset into a NumPy array. Code using .value should be updated to use NumPy indexing, using mydataset[. ] or mydataset[()] as appropriate."
I am using Julia's hdf5 library and the read operation is much faster (would include it as answer, but OP asked for python). The same hdf5 file read takes forever in h5py, however it is very manageable in Julia, worth learning to program in Julia just for this one problem. The only issue I had with Julia was that it didn't handle null terminated strings correctly, which for me was a bit of a roadblock.
Commenting on the answer itself, the list operation in the read version causes python to freeze. If I just do f[a_group_key] it works at the proper speed.
@demongolem: you should not use the listing of all keys of you already know which one you want to use. I have done it here to have a self-contained example that requires least amount of work to get something running.
If there are wheels for your platform (mac, linux, windows on x86) and you do not need MPI you can install h5py via pip:
With Enthought Canopy, use the GUI package manager or:
To install from source see Installation .
Core concepts¶
An HDF5 file is a container for two kinds of objects: datasets , which are array-like collections of data, and groups , which are folder-like containers that hold datasets and other groups. The most fundamental thing to remember when using h5py is:
Suppose someone has sent you a HDF5 file, mytestfile.hdf5 . (To create this file, read Appendix: Creating a file.) The very first thing you’ll need to do is to open the file for reading:
The File object is your starting point. What is stored in this file? Remember h5py.File acts like a Python dictionary, thus we can check the keys,
Based on our observation, there is one data set, mydataset in the file. Let us examine the data set as a Dataset object
The object we obtained isn’t an array, but an HDF5 dataset . Like NumPy arrays, datasets have both a shape and a data type:
They also support array-style slicing. This is how you read and write data from a dataset in the file:
Appendix: Creating a file¶
At this point, you may wonder how mytestdata.hdf5 is created. We can create a file by setting the mode to w when the File object is initialized. Some other modes are a (for read/write/create access), and r+ (for read/write access). A full list of file access modes and their meanings is at File Objects .
The File object has a couple of methods which look interesting. One of them is create_dataset , which as the name suggests, creates a data set of given shape and dtype
The File object is a context manager; so the following code works too
Groups and hierarchical organization¶
“HDF” stands for “Hierarchical Data Format”. Every object in an HDF5 file has a name, and they’re arranged in a POSIX-style hierarchy with / -separators:
The “folders” in this system are called groups . The File object we created is itself a group, in this case the root group , named / :
Creating a subgroup is accomplished via the aptly-named create_group . But we need to open the file in the “append” mode first (Read/write if exists, create otherwise)
All Group objects also have the create_* methods like File:
By the way, you don’t have to create all the intermediate groups manually. Specifying a full path works just fine:
Groups support most of the Python dictionary-style interface. You retrieve objects in the file using the item-retrieval syntax:
Iterating over a group provides the names of its members:
Membership testing also uses names:
You can even use full path names:
There are also the familiar keys() , values() , items() and iter() methods, as well as get() .
Since iterating over a group only yields its directly-attached members, iterating over an entire file is accomplished with the Group methods visit() and visititems() , which take a callable:
Attributes¶
One of the best features of HDF5 is that you can store metadata right next to the data it describes. All groups and datasets support attached named bits of data called attributes .
Attributes are accessed through the attrs proxy object, which again implements the dictionary interface:
Читайте также: