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]]
Try np.roll :np.roll(x, -1, axis=1).tolist()
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. ]])
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