1

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?

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

1 Answers1

2

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])
Divakar
  • 218,885
  • 19
  • 262
  • 358