Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert 0s into 2d array

I have an array x:

x = [0, -1, 0, 3]

and I want y:

y = [[0, -2, 0, 2],
     [0, -1, 0, 3],
     [0,  0, 0, 4]]

where the first row is x-1, the second row is x, and the third row is x+1. All even column indices are zero.

I'm doing:

y=np.vstack(x-1, x, x+1)
y[0][::2] = 0
y[1][::2] = 0
y[2][::2] = 0

I was thinking there might be a one-liner to do this instead of 4.

like image 753
A B Avatar asked Jan 08 '16 19:01

A B


People also ask

How do you make a 2D array zero in Python?

zeros = [ [0]*M for _ in range(N) ] # Use xrange if you're still stuck in the python2. x dark ages :). will also work and it avoids the nested list comprehension. If numpy isn't on the table, this is the form I would use.

Can you append to a 2D array?

Use the append() Function to Append Values to a 2D Array in Python.


1 Answers

In two lines

>>> x = np.array([0, -1, 0, 3])
>>> y = np.vstack((x-1, x, x+1))
>>> y[:,::2] = 0
>>> y
array([[ 0, -2,  0,  2],
       [ 0, -1,  0,  3],
       [ 0,  0,  0,  4]])

Explanation

y[:, ::2]

gives the full first dimension. i.e all rows and every other entry form the second dimension, i.e. the columns:

array([[-1, -1],
       [ 0,  0],
       [ 1,  1]])

This is different from:

y[:][::2]

because this works in two steps. Step one:

y[:]

gives a view of the whole array:

array([[-1, -2, -1,  2],
       [ 0, -1,  0,  3],
       [ 1,  0,  1,  4]])

Therefore, step two is doing essentially this:

y[::2]
array([[-1, -2, -1,  2],
       [ 1,  0,  1,  4]])

It works along the first dimension. i.e. the rows.

like image 197
Mike Müller Avatar answered Oct 14 '22 23:10

Mike Müller