Skip to content
This repository has been archived by the owner on Nov 4, 2023. It is now read-only.

Commit

Permalink
Merge pull request #52 from hoechenberger/col-names
Browse files Browse the repository at this point in the history
NF: Add join_multi_level_index()
  • Loading branch information
hoechenberger committed Feb 19, 2016
2 parents f7de123 + c7b5c8c commit fe59ba6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
19 changes: 18 additions & 1 deletion pphelper/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from __future__ import unicode_literals
import numpy as np
import pandas as pd
from pphelper.utils import add_zero_padding, get_max_from_list
from pphelper.utils import (add_zero_padding, get_max_from_list,
join_multi_level_index)


def test_add_zero_padding_no_args():
Expand Down Expand Up @@ -48,6 +49,22 @@ def test_get_max_from_list():
assert result == result_expected


def test_join_multi_level_index():
idx = pd.MultiIndex.from_arrays(
[['foo_1', 'bar_1', 'baz_1'],
['foo_2', 'bar_2', 'baz_2'],
['foo_3', 'bar_3', 'baz_3']],
names=['idx_1', 'idx_2', 'idx_3']
)

result_expected = ['foo_1-foo_2-foo_3',
'bar_1-bar_2-bar_3',
'baz_1-baz_2-baz_3']

result = join_multi_level_index(idx, sep='-')

assert result == result_expected

if __name__ == '__main__':
import pytest
pytest.main()
19 changes: 19 additions & 0 deletions pphelper/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,22 @@ def get_max_from_list(x):
"""
return np.array(list(itertools.chain.from_iterable(x))).max()


def join_multi_level_index(index, sep='_'):
"""
Parameters
----------
index : MultiIndex
The index to join.
sep : string, optional
The separator to insert between the joined index.
Defaults to an underscore (`_`).
Returns
-------
The joined index.
"""
return [sep.join(x) for x in index]

0 comments on commit fe59ba6

Please sign in to comment.