Bin elements per row - Vectorized 2D Bincount for NumPy

Viewed 1700

I have a NumPy array with integer values. Values of matrix range from 0 to max element in matrix(in other words, all numbers from 0 to max data element presented in it). I need to build effective( effective means fast fully-vectorized solution) for searching number of elements in each row and encode them according to matrix values.

I could not find a similar question, or a question that somehow helped to solve this.

So if i have this data in input:

# shape is (N0=4, m0=4) 
1   1   0   4
2   4   2   1
1   2   3   5
4   4   4   1

desired output is :

# shape(N=N0, m=data.max()+1):
1   2   0   0   1   0
0   1   2   0   1   0
0   1   1   1   0   1
0   1   0   0   3   0

I know how to solve this by simply counting unique values in each row of data iterating one by one, and then combining results taking in account all possible values in data array.

While using NumPy for vectorizing this the key problem is that searching each number one by one is slow and assuming that there are a lot of unique numbers presented, this can not be effective solution. Generally both N and unique numbers count is rather large(by the way, N seem to be larger than unique numbers count).

Has somebody have great ideas?)

1 Answers
Related