Skip to content

Instantly share code, notes, and snippets.

@joelcrocker
Last active December 28, 2015 20:19
Show Gist options
  • Save joelcrocker/7557018 to your computer and use it in GitHub Desktop.
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.
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)
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