0

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]]

5 Answers 5

2

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

2 Comments

but I need to use it in an big example that would not be sufficient
You can use any custom array instead of [0,1,3,2]. What else is required?
1

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.

Comments

1

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

Comments

1

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.

Comments

1
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

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.