Manipulation of arrays in python with numpy module

1

How do I do a rows swap of arrays using numpy?

I need this to implement the Gauss-Jordan method of partial pivotal linear systems.

    
asked by anonymous 28.11.2016 / 23:43

1 answer

1

If by "swap" you mean transpose lines x columns, you do so:

import numpy as np

teste = np.array([i for i in range(1,41)]).reshape((10,4))
print('Normal:')
print(teste)

print('Transposta:')
print(teste.T)

Result:

Normal:
[[ 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]]
Transposta:
[[ 1  5  9 13 17 21 25 29 33 37]
 [ 2  6 10 14 18 22 26 30 34 38]
 [ 3  7 11 15 19 23 27 31 35 39]
 [ 4  8 12 16 20 24 28 32 36 40]]

If, on the other hand, you mean to "trade" one line for the other, then you do it like this:

import numpy as np

teste = np.array([i for i in range(1,41)]).reshape((10,4))
print('Normal:')
print(teste)

print('Permutada:')
salva = np.copy(teste[1])
teste[1] = teste[5]
teste[5] = salva
print(teste)

Result:

Normal:
[[ 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]]
Permutada:
[[ 1  2  3  4]
 [21 22 23 24]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]
 [ 5  6  7  8]
 [25 26 27 28]
 [29 30 31 32]
 [33 34 35 36]
 [37 38 39 40]]
    
29.11.2016 / 00:03