savis
savis

Reputation: 19

Understanding numpy array slicing

I have an input array X.

[[68 72  2  0 15 74 34 20 36 3]
[20  2 79 20 80 45 15 20 11 45]
[42 13 80 35  3  3 38 70 74 75]
[80 20 78  5 34 13 80 11 20 72]
[20 13 15 20 13 75 81 20 75 13]
[20 32 15 20 29  2 75  3 45 80]
[72 74 80 20 64 45 79 74 20  1]
[37 20  6  5 15 20 80 45 29 20]
[15 20 13 75 80 65 15 35 20 60]
[20 75  2 13 78 20 15 45 20 72]]

Can someone help me understand the below code -

y = np.zeros_like(x)
y[:, :-1], y[:, -1] = x[:, 1:], x[:, 0]

Upvotes: 0

Views: 52

Answers (2)

perigon
perigon

Reputation: 2095

Shorthand for:

y = np.zeros_like(x)
y[:, :-1] = x[:, 1:]
y[:, -1] = x[:, 0]

Which translates to:

Make y an array of 0s of the same dimensions as x.

Set the part of y which includes all the rows and all columns except the last one equal to the part of x which includes all the rows and all columns except the first one.

Set the last column of y equal to the first column of x.

Basically, y will look like x except with the first column removed and tacked on at the end.

Upvotes: 0

Daniel F
Daniel F

Reputation: 14399

First:

y = np.zeros_like(x)

This creates an array full of zeros with the same size as x and stores it in y.

Then y[:, :-1], y[:, -1] <- all but the last column, and the last column

is set = to:

x[:, 1:], x[:, 0] <- all but the first column, and the first column.

It's a very inefficient way to roll the first column to the last.

A much better way to do this is

y = np.roll(x, -1, axis = 1)

Upvotes: 3

Related Questions