Skip to content

ENH: #10143 Function to walk the group hierarchy of a PyTables HDF5 file #10932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions doc/source/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2677,6 +2677,19 @@ everything in the sub-store and BELOW, so be *careful*.
store.remove('food')
store

You can walk through the group hierarchy using the ``walk`` method which
will yield a tuple for each group key along with the relative keys of its contents.

.. ipython:: python

for (path, subgroups, subkeys) in store.walk():
for subgroup in subgroups:
print('GROUP: {}/{}'.format(path, subgroup))
for subkey in subkeys:
key = '/'.join([path, subkey])
print('KEY: {}'.format(key))
print(store.get(key))

.. _io.hdf5-types:

Storing Mixed Types in a Table
Expand Down
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.17.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ Other enhancements

pd.concat([foo, bar, baz], 1)

- New method ``HDFStore.walk`` will recursively walk the group hierarchy of a HDF5 file (:issue:`10932`)

.. _whatsnew_0170.api:

.. _whatsnew_0170.api_breaking:
Expand Down
32 changes: 32 additions & 0 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,38 @@ def groups(self):
g._v_name != u('table')))
]

def walk(self):
""" Walk the pytables group hierarchy yielding the group name and pandas object names
for each group. Any non-pandas PyTables objects that are not a group will be ignored.

Returns
-------
A generator yielding tuples (`path`, `groups`, `leaves`) where:

- `path` is the full path to a group,
- `groups` is a list of group names contained in `path`
- `leaves` is a list of pandas object names contained in `path`

"""
_tables()
self._check_if_open()
for g in self._handle.walk_groups():
if getattr(g._v_attrs, 'pandas_type', None) is not None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this be is None?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, HDF5 groups that have 'pandas_type' attribute will be group wrappers around dataframe/series objects. Every Pandas object is wrapped in an HDF5 group.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh ok

continue

groups = []
leaves = []
for child in g._v_children.values():
pandas_type = getattr(child._v_attrs, 'pandas_type', None)
if pandas_type is None:
if isinstance(child, _table_mod.group.Group):
groups.append(child._v_name)
else:
leaves.append(child._v_name)

yield (g._v_pathname.rstrip('/'), groups, leaves)


def get_node(self, key):
""" return the node with the key or None if it does not exist """
self._check_if_open()
Expand Down
39 changes: 39 additions & 0 deletions pandas/io/tests/test_pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -4813,6 +4813,45 @@ def test_read_nokey(self):
df.to_hdf(path, 'df2', mode='a')
self.assertRaises(ValueError, read_hdf, path)

# GH10143
def test_walk(self):

objs = {
'df1': pd.DataFrame([1,2,3]),
'df2': pd.DataFrame([4,5,6]),
'df3': pd.DataFrame([6,7,8]),
'df4': pd.DataFrame([9,10,11]),
's1': pd.Series([10,9,8]),
'a1': np.array([[1,2,3], [4,5,6]])
}

with ensure_clean_store('walk_groups.hdf', mode='w') as store:
store.put('/first_group/df1', objs['df1'])
store.put('/first_group/df2', objs['df2'])
store.put('/second_group/df3', objs['df3'])
store.put('/second_group/s1', objs['s1'])
store.put('/second_group/third_group/df4', objs['df4'])
g1 = store._handle.get_node('/first_group')
store._handle.create_array(g1, 'a1', objs['a1'])

expect = {
'': (set(['first_group', 'second_group']), set()),
'/first_group': (set(), set(['df1', 'df2'])),
'/second_group': (set(['third_group']), set(['df3', 's1'])),
'/second_group/third_group': (set(), set(['df4'])),
}

for path, groups, leaves in store.walk():
self.assertIn(path, expect)
expect_groups, expect_frames = expect[path]

self.assertEqual(expect_groups, set(groups))
self.assertEqual(expect_frames, set(leaves))
for leaf in leaves:
frame_path = '/'.join([path, leaf])
df = store.get(frame_path)
self.assert_(df.equals(objs[leaf]))


class TestHDFComplexValues(Base):
# GH10447
Expand Down