Reputation: 893
I want to perform a swap between lines in np.array in python. What I want is to take the first line of the array and put it in the end of the array. I have the code that you can swap two rows which is the following:
import numpy as np
my_array = np.arrange(25).reshape(5, 5)
print my_array, '\n'
def swap_rows(arr, frm, to):
arr[[frm, to],:] = arr[[to, frm],:]
//swap_rows(my_array, 0, 8)
//print my_array
my_array[-1] = my_array[0]
print my_array
But this code performs the swap between first and last row. I want just to put the first line in the end. How can I do so?
The initial matrix is the following:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
The desired outcome is the following:
[[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[ 0 1 2 3 4]]
EDIT: I am trying to do the same in my matrix which is the following:
But it doesnt change anything. My code is the following:
initial_data.append(copy.deepcopy(tab))
initial_data2 = np.asarray(initial_data)
initial_data3 = np.roll(initial_data2, -1, axis=0)
I am getting the same array.
Upvotes: 1
Views: 4141
Reputation: 221584
You can use np.roll
-
np.roll(my_array,-1,axis=0)
Sample run -
In [53]: my_array
Out[53]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])
In [54]: np.roll(my_array,-1,axis=0)
Out[54]:
array([[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8]])
Upvotes: 2