Reputation: 125
lets assume that i have a numpy array and its like this:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]]
and I like to have a new numpy array, that the first half exactly the same as array above but second half it should be started from the bottom till it reaches the half of array. how do I do that?
EDIT: The method i need it has to work for an array with 60000 elements. not for this simple example!!
Output should be like this:
[[1, 2, 3],
[4, 5, 6],
[10, 11, 12],
[7, 8, 9]]
Upvotes: 0
Views: 313
Reputation: 36
array = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
n = (int)(array.shape[0]//2) # change n accordingly
# n is the row number from which you want to start the reversal
temp = array[n:]
temp = temp[::-1]
array[n:] = temp
Upvotes: 1
Reputation: 3497
Takes always half the array as requested. (Based on mathfux's answer)
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
sl = range(0, len(array)//2)
s2 = reversed(range(len(array)//2, len(array)))
b = array[(*sl, *s2), :]
print(b)
prints
[[ 1 2 3]
[ 4 5 6]
[10 11 12]
[ 7 8 9]]
Of course cou could just index the last half:
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
from_to = tuple(range(len(array)//2, len(array)))
to_from = tuple(reversed(from_to))
array[from_to, :] = array[to_from, :]
print(array)
Same result.
Upvotes: 1
Reputation: 1712
Another solution would be to simply swap the rows with an assignment, like:
arr[2], arr[3] = arr[3], arr[2]
After your edit, here's a solution that inverts just the bottom half of the array:
arr = np.array([[...],...])
arr[int(len(a)/2):] = arr[int(len(a)/2):][::-1]
[::-1]
returns the elements of an array in reverse order. So applying it to the bottom half of the original array and assigning this new array to the bottom half of the original array will give you an array with the first n/2 rows unchanged and last n/2 rows in reverse order.
Upvotes: 1
Reputation: 46
This might be kinda crude but you simply need to replace the 3rd (index = 2) row in array e with the 4th (index = 3) row. 'a' is a placeholder for switching the 3rd and 4th row.
for i in range(len(e)):
if i == 2:
a = e[i]
e[i] = e[3]
if i == 3:
e[i] = a
Upvotes: 1
Reputation: 5939
Use numpy indexes:
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
array[[0,1,3,2], :]
array([[ 1, 2, 3],
[ 4, 5, 6],
[10, 11, 12],
[ 7, 8, 9]])
Upvotes: 2