Skip to content

Commit

Permalink
Column.get(map=) support dicts with partial keys (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
hagenw authored Nov 6, 2023
1 parent 5152318 commit 69332d4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
26 changes: 18 additions & 8 deletions audformat/core/column.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,20 +254,30 @@ def get(
"for its labels."
)

# Check that at least one key is available for map
# if labels are stored as dictionary
keys = []
for key, value in labels.items():
if isinstance(value, dict):
keys += list(value.keys())
keys = sorted(list(set(keys)))
if len(keys) > 0 and map not in keys:
raise ValueError(
f"Cannot map "
f"'{self._id}' "
f"to "
f"'{map}'. "
f"Expected one of "
f"{list(keys)}."
)

mapping = {}
for key, value in labels.items():
if isinstance(value, dict):
if map in value:
value = value[map]
else:
raise ValueError(
f"Cannot map "
f"'{self._id}' "
f"to "
f"'{map}'. "
f"Expected one of "
f"{list(value)}."
)
value = np.NaN
mapping[key] = value

result = result.map(mapping)
Expand Down
5 changes: 5 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@


pytest.DB = audformat.testing.create_db()
# Adjust scheme dictionary to contain one missing label
labels = pytest.DB.schemes["label_map_str"].labels
labels['label3'].pop('prop2')
pytest.DB.schemes["label_map_str"].replace_labels(labels)

pytest.DB_ROOT = 'db'
pytest.FILE_DUR = pd.to_timedelta('1s')

Expand Down
7 changes: 5 additions & 2 deletions tests/test_column.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def test_get_as_segmented():
pytest.DB['files']['string'], 'map', None,
marks=pytest.mark.xfail(raises=ValueError),
),
pytest.param( # no labels
pytest.param( # no labels in dict
pytest.DB['files']['label_map_str'], 'bad', None,
marks=pytest.mark.xfail(raises=ValueError),
),
Expand All @@ -189,7 +189,10 @@ def test_map(column, map, expected_dtype):
mapping = {}
for key, value in pytest.DB.schemes[column.scheme_id].labels.items():
if isinstance(value, dict):
value = value[map]
if map in value:
value = value[map]
else:
value = np.NaN
mapping[key] = value
expected = expected.map(mapping).astype(expected_dtype)
expected.name = map
Expand Down

0 comments on commit 69332d4

Please sign in to comment.