Skip to content
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

Add DataTree.match_names to match node names #9439

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
45 changes: 45 additions & 0 deletions xarray/core/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,51 @@ def match(self, pattern: str) -> DataTree:
}
return DataTree.from_dict(matching_nodes, name=self.root.name)

def match_names(self, names: Iterable[str]) -> DataTree:
"""
Filter nodes by name.

Parameters
----------
names: Iterable[str]
The list of node names to retain.

Returns
-------
DataTree

See Also
--------
match
filter
pipe
map_over_subtree

Examples
--------
>>> dt = DataTree.from_dict(
... {
... "/a/A": None,
... "/a/B": None,
... "/a/C": None,
... "/C/D": None,
... "/E/F": None,
... }
... )
>>> dt.match_names(["A", "C"])
<xarray.DataTree>
Group: /
├── Group: /C
└── Group: /a
├── Group: /a/A
└── Group: /a/C
"""
names = set(names)
matching_nodes = {
node.path: node.ds for node in self.subtree if node.name in names
}
return DataTree.from_dict(matching_nodes, name=self.root.name)

def map_over_subtree(
self,
func: Callable,
Expand Down
21 changes: 21 additions & 0 deletions xarray/tests/test_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,27 @@ def test_match(self):
)
assert_identical(result, expected)

def test_match_names(self):
# TODO is this example going to cause problems with case sensitivity?
dt: DataTree = DataTree.from_dict(
{
"/a/A": None,
"/a/B": None,
"/a/C": None,
"/C/D": None,
"/E/F": None,
}
)
result = dt.match_names(["A", "C"])
expected = DataTree.from_dict(
{
"/a/A": None,
"/a/C": None,
"/C": None,
}
)
assert_identical(result, expected)

def test_filter(self):
simpsons: DataTree = DataTree.from_dict(
d={
Expand Down
Loading