Python: Operações com Matrizes do módulo Numpy

From Wiki

Operações com Matrizes

Usando o tipo array

#!/usr/bin/python
from numpy import *

arr =  array(
   [
       [1,2,3,4,5,6],
       [7,8,9,10,11,12]  
   ])

print("arr: \n", arr)
print()
print("dimensions: ", arr.ndim)
print("shape (rows,colums): ", arr.shape)
print("size: ", arr.size) 

arr2 = arr.flatten()
print("arr.flatten: ", arr2)

arr3 = arr.reshape(3,4)
print("arr.reshape: \n", arr3)

arr4 = arr.reshape(2,2,3)
print("arr.reshape: \n", arr4)

Resultado:

arr:
[[ 1  2  3  4  5  6]
[ 7  8  9 10 11 12]]

dimensions:  2
shape (rows,colums):  (2, 6)
size:  12
arr.flatten:  [ 1  2  3  4  5  6  7  8  9 10 11 12]
arr.reshape:
[[ 1  2  3  4]
[ 5  6  7  8]
[ 9 10 11 12]]

arr.reshape:
[[[ 1  2  3]
 [ 4  5  6]]

[[ 7  8  9]
 [10 11 12]]]

Usando o tipo matrix

#!/usr/bin/python
from numpy import *

m = matrix('1 2 3; 6 9 2; 2 6 9')
m2 = matrix('2 3 1; 2 1 6; 5 4 2')

print("m:")
print(m) 

print("m.max:\n", m.max())

m3 = m + m2
print("m2:")
print(m2)
print("m3 = m + m2 :")
print(m3)

resultado:

m:
[[1 2 3]
 [6 9 2]
 [2 6 9]]
m.max:
9
m2:
[[2 3 1]
 [2 1 6]
 [5 4 2]]
m3 = m + m2 :
[[ 3  5  4]
 [ 8 10  8]
 [ 7 10 11]]

Ver também