2

I have a NumPy array, which I want to move the first element to the end. I know how to do it by converting to the list and do the insert operation but I want to avoid this and do it in a better and optimized way.

Suppose this is my array and I want to move 0 to the end:

x = [[ 0 388.13 19.346 412.38 39.594]
    [ 0 388.15 8.5168 416 38.972] 
    [ 0 223.14 156.21 317.91 193.46]]

I know I can do it in this way by converting to the list:

X = X.tolist()
for ele in x:
    ele.insert(len(ele), ele.pop(0))

Is there any way to do it without converting it to a list (using numpy)? and also, the way I'm doing is not efficient, What is a possible way to make my code efficient in term of speed even by converting it to list?

Expected output:

x = [[388.13 19.346 412.38 39.594 0]
    [388.15 8.5168 416 38.972 0] 
    [223.14 156.21 317.91 193.46 0]]
3
  • What output do you expect? Commented Nov 15, 2020 at 19:18
  • You can store the first element in temp variable then do np.delete() then np.append() just remember to reshape your array. Commented Nov 15, 2020 at 19:25
  • One way or other you'll have to copy all values of the array to a new location, either in this array or a new one. numpy does not a use a linked list storage where such a move would just require changing a few pointers. Commented Nov 15, 2020 at 22:05

2 Answers 2

11

Try np.roll :np.roll(x, -1, axis=1).tolist()

Sign up to request clarification or add additional context in comments.

Comments

6

you could also try np.hstack:

np.hstack([x[:, 1:], x[:, :1]])

or even np.concatenate:

np.concatenate([x[:, 1:], x[:, :1]],  axis=1)

or even np.c_

np.c_[x[:, 1:], x[:, :1]]

all the above gives you:

array([[388.13  ,  19.346 , 412.38  ,  39.594 ,   0.    ],
       [388.15  ,   8.5168, 416.    ,  38.972 ,   0.    ],
       [223.14  , 156.21  , 317.91  , 193.46  ,   0.    ]])

1 Comment

You beat me to it! Well played.

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.