Changing lines of an array - Python Pandas

Asked

Viewed 402 times

3

I have an array and need to change the order of the lines.

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

I need it like this:

array([[ 5,  6,  7,  8,  9],
       [ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

I tried to use the .reindex but I didn’t succeed, what would be the best way to do that?

import numpy as np

arr = np.arange(25)
arr = arr.reshape(5,5)

print('array inicial:')
print(arr)

print('array com as linhas 0 e 1 trocadas entre si:')

Needed to do this using numpy library

  • If your program first creates the list and then inserts it into the array, it would be more interesting to deal with list.pop() before insertion.

2 answers

2


Change the lines directly:

arr[[0, 1]] = arr[[1, 0]]

import numpy as np

arr = np.arange(25)
arr = arr.reshape(5,5)

print('array inicial:')
print(arr)

#Troca a posição das linhas 0 e 1 
arr[[0, 1]] = arr[[1, 0]]


print('array com as linhas 0 e 1 trocadas entre si:')
print(arr)

resulting:

array inicial:
[[ 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]]
array com as linhas 0 e 1 trocadas entre si:
[[ 5  6  7  8  9]
 [ 0  1  2  3  4]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

Code in the Repl.it

  • 1

    Thanks, it all worked out!

1

To perform this change, it is possible to indicate the desired order of the rows in a list (or tuple) directly in the array indexing:

arr = arr[[1,0,2,3,4],:]

After ordering:

In [14]: arr
Out[14]:
array([[ 5,  6,  7,  8,  9],
       [ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

The result is a copy (not a view) of the original array with the ordered lines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.