0

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]
1
  • Have you tried the code to see what it does? Commented Jul 25, 2017 at 6:40

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.