Skip to content
Advertisement

Python Group Values in a Nested List At Corresponding Indexes

Given a list nested with numpy lists, I want to go through each index in each corresponding list and keep track of the count depending on the element, which would be stored into a single list.

The minimum runnable code example below better showcases the problem.

JavaScript

I have looked into from collections import defaultdict and from itertools import groupby, but I couldn’t understand how to use that to do anything else but sort a nested list.

Apologies if this issue is within the two sources I provided above.

Advertisement

Answer

If all the inner arrays have the same length you could transform it into a 2-dimensional array to leverage numpy vectorization:

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement