ScalaBoy
ScalaBoy

Reputation: 3392

How to transfer 2-D array into a 1-D array?

I have 2-D numpy array arr:

array([[0., 1., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [0., 0., 1.],
       [1., 0., 0.],
       [1., 0., 0.]]

I want to convert it to a 1-D vector:

vec = [1, 0, 0, 2, 0, 0]

The values 0, 1 and 2 should correspond to a column of art, in which the value is equal to 1.

Is there any non-for loop way to do it?

Upvotes: 1

Views: 208

Answers (3)

Samer Ayoub
Samer Ayoub

Reputation: 1001

>>> a.nonzero()[1]
array([1, 0, 0, 2, 0, 0], dtype=int64)

For more flexible conditions

>>> np.nonzero(a==1)[1]
array([1, 0, 0, 2, 0, 0], dtype=int64)

>>> np.where(a==1)[1]
array([1, 0, 0, 2, 0, 0], dtype=int64)

>>> np.where(a>0)[1]
array([1, 0, 0, 2, 0, 0], dtype=int64)

Upvotes: 0

Joe Profeta
Joe Profeta

Reputation: 1

You can use matrix math to solve this because you have only one non-zero value per row. A simple dot-product with a "position" vector will give you the desired output. You want to emulate the matrix equation A*x = y, and so long as x is a column vector, you will end up with a column vector as the answer.

>>> import numpy as np
>>> a = np.array([[0., 1., 0.],
...               [1., 0., 0.],
...               [1., 0., 0.],
...               [0., 0., 1.],
...               [1., 0., 0.],
...               [1., 0., 0.]])
>>> x = (0,1,2)
>>> y = np.dot(a,x)
>>> y
array([1., 0., 0., 2., 0., 0.])

Using this method, you can change your "position" vector to be whatever you want and it will "index" appropriately (I put that in quotes since it is a math trick). For example:

>>> x = (2,4,8)
>>> np.dot(a,x)
array([4., 2., 2., 8., 2., 2.])

Upvotes: 0

Sash Sinha
Sash Sinha

Reputation: 22473

Try numpy.nonzero:

>>> import numpy as np
>>> a = np.array([[0., 1., 0.],
...               [1., 0., 0.],
...               [1., 0., 0.],
...               [0., 0., 1.],
...               [1., 0., 0.],
...               [1., 0., 0.]])
>>> np.nonzero(a)[1]
array([1, 0, 0, 2, 0, 0])

or numpy.where:

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

Upvotes: 1

Related Questions