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

From Wiki
Revision as of 02:49, 28 September 2018 by Ebasso (talk | contribs)

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

>>> print id(arr)
4532265248.  # igual pois é um alias
>>> print id(arr2)
4532265248 # igual pois é um alias
>>> arr2 = arr.view()
>>> print id(arr2)
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