Some comments or a docstring here would be nice. There's a lot of transformations happening here & having some clue about what the sample input/output look like might be helpful.