I want to create a numpy array that contains how many times a value (between 1-3) occurs in a specific place. For example, if I have:
a = np.array([[1,2,3], [3,2,1], [2,1,3], [1,1,1]])
I want to return an array like this:
[[[ 1 0 0] [ 0 1 0] [ 0 0 1]] [[ 0 0 1] [ 0 1 0] [ 1 0 0]] [[ 0 1 0] [ 1 0 0] [ 0 0 1]] [[ 1 0 0] [ 1 0 0] [ 1 0 0]]]
Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 - once in the third position, 1 - once in the fourth position, etc. Later I will have more input arrays of the same sizes, and I would like to add values ββto this counter array to the general values.
The code I have now is:
a = np.array([[1,2,3], [3,2,1], [2,1,3], [1,1,1]]) cumulative = np.zeros((4,3,3)) for r in range(len(cumulative)): for c in range(len(cumulative[0])): cumulative[r, c, a[r,c]-1] +=1
This gives me the result I want. However, I would like to condense the for loops on one line using the following line:
cumulative[:, :, a[:, :]-1] +=1
This line does not work, and I can not find anything on the Internet on how to perform this operation. Any suggestions?