Last active
December 28, 2015 20:19
-
-
Save joelcrocker/7557018 to your computer and use it in GitHub Desktop.
Tuple grouping function. Useful for collapsing tabular data from left to right. Uses toolz; see http://toolz.readthedocs.org/en/latest/ See usage.txt below for examples.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from toolz.itertoolz.core import reduceby | |
from toolz.dicttoolz.core import valmap | |
def group_tuples(tuples): | |
if len(tuples[0]) < 2: | |
return [t[0] for t in tuples] | |
result = reduceby( | |
lambda t: t[0], | |
lambda a, b: a + [b[1:]], | |
tuples, | |
[] | |
) | |
with_counts = dict( | |
((k, len(v)), v) for (k, v) in result.items() | |
) | |
return valmap(group_tuples, with_counts) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Usage: | |
>>> tuples = [ | |
('t1', 'c1', 'namex'), | |
('t1', 'c1', 'namey'), | |
('t2', 'c1', 'namey'), | |
('t1', 'c3', 'nameyt') | |
] | |
>>> group_tuples(tuples) | |
{('t1', 3): {('c1', 2): ['namex', 'namey'], ('c3', 1): ['nameyt']}, | |
('t2', 1): {('c1', 1): ['namey']}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment