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.
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.
Use the append() Function to Append Values to a 2D Array in Python.
>>> 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]])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With