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
x
20
20
1
import numpy as np
2
3
4
lst = [
5
np.array([1,0,1]),
6
np.array([1,1,1]),
7
np.array([2,2,1])
8
]
9
print(lst)
10
11
#Problem, take count of each corresponding index within list
12
#If the element == 2, subtract one. If it's 1, add 1. 0 has no value
13
#Make the output just one list with the calculated count for each index
14
15
#Expected output:
16
#lst = [1, 0, 3]
17
# 1 in index 0 because there's two 1s in each lists first index, but a 2 subtracts one from the count
18
# 0 in index 1 since there's one 1 which brings the count to 1, but a 2 subtracts one from the count
19
# 3 in index 2 since there's three 1's, adding 3 to the count.
20
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
1
11
11
1
# transform into two dimensional array
2
arr = np.array(lst)
3
4
# set -1 where values are equals to 2
5
t = np.where(arr == 2, -1, arr)
6
7
# sum across first axis (each corresponding positions on the inners lists)
8
res = t.sum(axis=0).tolist()
9
10
print(res)
11
Output
JavaScript
1
2
1
[1, 0, 3]
2