I have a 2d numpy array., A
I want to apply np.bincount()
to each column of the matrix A
to generate another 2d array B
that is composed of the bincounts of each column of the original matrix A
.
My problem is that np.bincount() is a function that takes a 1d array-like. It's not an array method like B = A.max(axis=1)
for example.
Is there a more pythonic/numpythic way to generate this B
array other than a nasty for-loop?
import numpy as np
states = 4
rows = 8
cols = 4
A = np.random.randint(0,states,(rows,cols))
B = np.zeros((states,cols))
for x in range(A.shape[1]):
B[:,x] = np.bincount(A[:,x])
bincount() method counts the occurrence of each element. Each bin value is the occurrence of its index. One can also set the bin size accordingly.
The BIN Count function counts the frequency by incrementing the BIN count corresponding to the BIN Sorting result by 1 each time the measurement ends. The frequency of each BIN can be viewed on the display when necessary.
Using the same philosophy as in this post
, here's a vectorized approach -
m = A.shape[1]
n = A.max()+1
A1 = A + (n*np.arange(m))
out = np.bincount(A1.ravel(),minlength=n*m).reshape(m,-1).T
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With