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

From Wiki

Operações com Arrays

Criando um array com o Numpy

>>> from numpy import *
>>> arr = array([1,2,4,7,5,9])
>>> print(arr)
[1 2 4 7 5 9]
>>> print(arr.dtype)
int64
>>> arr = array([1,2,4,7,5.3])
>>> print(arr)
[ 1.   2.   4.   7.   5.3]
>>>print(arr.dtype)
float64

Operações Vetorizadas

>>> arr = array([2,4,7,6,1])
>>> arr = arr + 5
>>> print(arr)
[ 7  9 12 11  6]
>>> print pow(arr,2)
[ 49  81 144 121  36]
>>> arr2 = array([3,1,-2,-1,4])
>>> arr3 = arr + arr2
>>> print(arr3)
[10 10 10 10 10]

Copia de arrays

>>> arr = array([1,3,9,8,2])
>>> arr2 = arr
>>> arr3 = arr.view()
>>> arr4 = arr.copy()
>>> arr[1] = 7
>>> print(arr)
[1 7 9 8 2]
>>> print(arr2)
[1 7 9 8 2]
>>> print(arr3)
[1 7 9 8 2]
>>> print(arr4)
[1 3 9 8 2]
>>> print(id(arr))
4518341328
>>> print(id(arr2))
4518341328
>>> print(id(arr3))
4518341008
>>> print(id(arr4))
4532265488

Outros tipos de array

arange

>>> arr = arange(1,15,2)
>>> print arr
[ 1  3  5  7  9 11 13]

zeros

>>> arr = zeros(5)
>>> print arr
[ 0.  0.  0.  0.  0.]

ones

>>> arr = ones(7)
>>> print arr
[ 1.  1.  1.  1.  1.  1.  1.]
>>> arr = ones(7,int)
>>> print arr
[1 1 1 1 1 1 1]

logspace

>>> arr = logspace(1,15,2)
>>> print arr
[  1.00000000e+01   1.00000000e+15]

linspace

Cria partes

>>> arr = linspace(0,2,3) 
>>> print arr
[ 0.  1.  2.]
>>> arr = linspace(0,5,4)
>>> print arr
[ 0.          1.66666667  3.33333333  5.        ]

Ver também