Suzan Cioc Suzan Cioc - 1 year ago 56
Python Question

How to convert stack of rows of binary digits into column of values in Python?

Suppose I have

>>> np.array([[0,0],[0,1],[1,0],[1,1]])
array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])


This is a matrix, each of lines of which can be regarded as binary representation of some number, so it is

>>> np.array([[0],[1],[2],[3]])
array([[0],
[1],
[2],
[3]])


How to calculate this transformation in shortest way in Python?

Answer Source

You can use matrix-multiplication with np.dot to do element-wise scaling of each column with appropriate 2-powered numbers and then sum-reduce each row, leading us to few approaches -

a.dot(2**np.arange(a.shape[1]-1,-1,-1))
a[:,::-1].dot(2**np.arange(a.shape[1]))
a.dot(1 << np.arange(a.shape[1])[::-1])

Sample run -

In [557]: a = np.array([[0,0],[0,1],[1,0],[1,1]])

In [558]: a.dot(2**np.arange(a.shape[1]-1,-1,-1))
Out[558]: array([0, 1, 2, 3])

In [559]: a[:,::-1].dot(2**np.arange(a.shape[1]))
Out[559]: array([0, 1, 2, 3])

In [566]: a.dot(1 << np.arange(a.shape[1])[::-1])
Out[566]: array([0, 1, 2, 3])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download