Data Science Academy - Python Fundamentos - Capítulo 8

Download: http://github.com/dsacademybr


In [1]:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())

NumPy

Para importar numpy, utilize: import numpy as np

Você também pode utilizar: from numpy import * . Isso evitará a utilização de np., mas este comando importará todos os módulos do NumPy.

Para atualizar o NumPy, abra o prompt de comando e digite: pip install numpy -U


In [2]:
# Importando o NumPy
import numpy as np

In [3]:
np.__version__


Out[3]:
'1.18.2'

Criando Arrays


In [4]:
# Help
help(np.array)


Help on built-in function array in module numpy:

array(...)
    array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
    
    Create an array.
    
    Parameters
    ----------
    object : array_like
        An array, any object exposing the array interface, an object whose
        __array__ method returns an array, or any (nested) sequence.
    dtype : data-type, optional
        The desired data-type for the array.  If not given, then the type will
        be determined as the minimum type required to hold the objects in the
        sequence.
    copy : bool, optional
        If true (default), then the object is copied.  Otherwise, a copy will
        only be made if __array__ returns a copy, if obj is a nested sequence,
        or if a copy is needed to satisfy any of the other requirements
        (`dtype`, `order`, etc.).
    order : {'K', 'A', 'C', 'F'}, optional
        Specify the memory layout of the array. If object is not an array, the
        newly created array will be in C order (row major) unless 'F' is
        specified, in which case it will be in Fortran order (column major).
        If object is an array the following holds.
    
        ===== ========= ===================================================
        order  no copy                     copy=True
        ===== ========= ===================================================
        'K'   unchanged F & C order preserved, otherwise most similar order
        'A'   unchanged F order if input is F and not C, otherwise C order
        'C'   C order   C order
        'F'   F order   F order
        ===== ========= ===================================================
    
        When ``copy=False`` and a copy is made for other reasons, the result is
        the same as if ``copy=True``, with some exceptions for `A`, see the
        Notes section. The default order is 'K'.
    subok : bool, optional
        If True, then sub-classes will be passed-through, otherwise
        the returned array will be forced to be a base-class array (default).
    ndmin : int, optional
        Specifies the minimum number of dimensions that the resulting
        array should have.  Ones will be pre-pended to the shape as
        needed to meet this requirement.
    
    Returns
    -------
    out : ndarray
        An array object satisfying the specified requirements.
    
    See Also
    --------
    empty_like : Return an empty array with shape and type of input.
    ones_like : Return an array of ones with shape and type of input.
    zeros_like : Return an array of zeros with shape and type of input.
    full_like : Return a new array with shape of input filled with value.
    empty : Return a new uninitialized array.
    ones : Return a new array setting values to one.
    zeros : Return a new array setting values to zero.
    full : Return a new array of given shape filled with value.
    
    
    Notes
    -----
    When order is 'A' and `object` is an array in neither 'C' nor 'F' order,
    and a copy is forced by a change in dtype, then the order of the result is
    not necessarily 'C' as expected. This is likely a bug.
    
    Examples
    --------
    >>> np.array([1, 2, 3])
    array([1, 2, 3])
    
    Upcasting:
    
    >>> np.array([1, 2, 3.0])
    array([ 1.,  2.,  3.])
    
    More than one dimension:
    
    >>> np.array([[1, 2], [3, 4]])
    array([[1, 2],
           [3, 4]])
    
    Minimum dimensions 2:
    
    >>> np.array([1, 2, 3], ndmin=2)
    array([[1, 2, 3]])
    
    Type provided:
    
    >>> np.array([1, 2, 3], dtype=complex)
    array([ 1.+0.j,  2.+0.j,  3.+0.j])
    
    Data-type consisting of more than one element:
    
    >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
    >>> x['a']
    array([1, 3])
    
    Creating an array from sub-classes:
    
    >>> np.array(np.mat('1 2; 3 4'))
    array([[1, 2],
           [3, 4]])
    
    >>> np.array(np.mat('1 2; 3 4'), subok=True)
    matrix([[1, 2],
            [3, 4]])


In [5]:
# Array criado a partir de uma lista:
vetor1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])

In [6]:
print(vetor1)


[0 1 2 3 4 5 6 7 8]

In [7]:
# Um objeto do tipo ndarray é um recipiente multidimensional de itens do mesmo tipo e tamanho.
type(vetor1)


Out[7]:
numpy.ndarray

In [8]:
# Usando métodos do array NumPy
vetor1.cumsum()


Out[8]:
array([ 0,  1,  3,  6, 10, 15, 21, 28, 36])

In [9]:
# Criando uma lista. Perceba como listas e arrays são objetos diferentes, com diferentes propriedades
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8]

In [10]:
lst


Out[10]:
[0, 1, 2, 3, 4, 5, 6, 7, 8]

In [11]:
type(lst)


Out[11]:
list

In [12]:
# Imprimindo na tela um elemento específico no array
vetor1[0]


Out[12]:
0

In [13]:
# Alterando um elemento do array
vetor1[0] = 100

In [14]:
print(vetor1)


[100   1   2   3   4   5   6   7   8]

In [15]:
# Não é possível incluir elemento de outro tipo
vetor1[0] = 'Novo elemento'


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-982158d30410> in <module>
      1 # Não é possível incluir elemento de outro tipo
----> 2 vetor1[0] = 'Novo elemento'

ValueError: invalid literal for int() with base 10: 'Novo elemento'

In [16]:
# Verificando o formato do array
print(vetor1.shape)


(9,)

Funções NumPy


In [17]:
# A função arange cria um vetor contendo uma progressão aritmética a partir de um intervalo - start, stop, step
vetor2 = np.arange(0., 4.5, .5)

In [18]:
print(vetor2)


[0.  0.5 1.  1.5 2.  2.5 3.  3.5 4. ]

In [19]:
# Verificando o tipo do objeto
type(vetor2)


Out[19]:
numpy.ndarray

In [20]:
# Formato do array
np.shape(vetor2)


Out[20]:
(9,)

In [21]:
print (vetor2.dtype)


float64

In [22]:
x = np.arange(1, 10, 0.25)
print(x)


[1.   1.25 1.5  1.75 2.   2.25 2.5  2.75 3.   3.25 3.5  3.75 4.   4.25
 4.5  4.75 5.   5.25 5.5  5.75 6.   6.25 6.5  6.75 7.   7.25 7.5  7.75
 8.   8.25 8.5  8.75 9.   9.25 9.5  9.75]

In [23]:
print(np.zeros(10))


[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

In [24]:
# Retorna 1 nas posições em diagonal e 0 no restante
z = np.eye(3)

In [25]:
z


Out[25]:
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

In [26]:
# Os valores passados como parâmetro, formam uma diagonal
d = np.diag(np.array([1, 2, 3, 4]))

In [27]:
d


Out[27]:
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])

In [28]:
# Array de números complexos
c = np.array([1+2j, 3+4j, 5+6*1j])

In [29]:
c


Out[29]:
array([1.+2.j, 3.+4.j, 5.+6.j])

In [30]:
# Array de valores booleanos
b = np.array([True, False, False, True])

In [31]:
b


Out[31]:
array([ True, False, False,  True])

In [32]:
# Array de strings
s = np.array(['Python', 'R', 'Julia'])

In [33]:
s


Out[33]:
array(['Python', 'R', 'Julia'], dtype='<U6')

In [34]:
# O método linspace (linearly spaced vector) retorna um número de 
# valores igualmente distribuídos no intervalo especificado 
np.linspace(0, 10)


Out[34]:
array([ 0.        ,  0.20408163,  0.40816327,  0.6122449 ,  0.81632653,
        1.02040816,  1.2244898 ,  1.42857143,  1.63265306,  1.83673469,
        2.04081633,  2.24489796,  2.44897959,  2.65306122,  2.85714286,
        3.06122449,  3.26530612,  3.46938776,  3.67346939,  3.87755102,
        4.08163265,  4.28571429,  4.48979592,  4.69387755,  4.89795918,
        5.10204082,  5.30612245,  5.51020408,  5.71428571,  5.91836735,
        6.12244898,  6.32653061,  6.53061224,  6.73469388,  6.93877551,
        7.14285714,  7.34693878,  7.55102041,  7.75510204,  7.95918367,
        8.16326531,  8.36734694,  8.57142857,  8.7755102 ,  8.97959184,
        9.18367347,  9.3877551 ,  9.59183673,  9.79591837, 10.        ])

In [35]:
print(np.linspace(0, 10, 15))


[ 0.          0.71428571  1.42857143  2.14285714  2.85714286  3.57142857
  4.28571429  5.          5.71428571  6.42857143  7.14285714  7.85714286
  8.57142857  9.28571429 10.        ]

In [36]:
print(np.logspace(0, 5, 10))


[1.00000000e+00 3.59381366e+00 1.29154967e+01 4.64158883e+01
 1.66810054e+02 5.99484250e+02 2.15443469e+03 7.74263683e+03
 2.78255940e+04 1.00000000e+05]

Criando Matrizes


In [37]:
# Criando uma matriz
matriz = np.array([[1,2,3],[4,5,6]])

In [38]:
print(matriz)


[[1 2 3]
 [4 5 6]]

In [39]:
print(matriz.shape)


(2, 3)

In [40]:
# Criando uma matriz 2x3 apenas com números "1"
matriz1 = np.ones((2,3))

In [41]:
print(matriz1)


[[1. 1. 1.]
 [1. 1. 1.]]

In [42]:
# Criando uma matriz a partir de uma lista de listas
lista = [[13,81,22], [0, 34, 59], [21, 48, 94]]

In [43]:
# A função matrix cria uma matria a partir de uma sequência
matriz2 = np.matrix(lista)

In [44]:
matriz2


Out[44]:
matrix([[13, 81, 22],
        [ 0, 34, 59],
        [21, 48, 94]])

In [45]:
type(matriz2)


Out[45]:
numpy.matrix

In [46]:
# Formato da matriz
np.shape(matriz2)


Out[46]:
(3, 3)

In [47]:
matriz2.size


Out[47]:
9

In [48]:
print(matriz2.dtype)


int64

In [49]:
matriz2.itemsize


Out[49]:
8

In [50]:
matriz2.nbytes


Out[50]:
72

In [51]:
print(matriz2[2,1])


48

In [52]:
# Alterando um elemento da matriz
matriz2[1,0] = 100

In [53]:
matriz2


Out[53]:
matrix([[ 13,  81,  22],
        [100,  34,  59],
        [ 21,  48,  94]])

In [54]:
x = np.array([1, 2])  # NumPy decide o tipo dos dados
y = np.array([1.0, 2.0])  # NumPy decide o tipo dos dados
z = np.array([1, 2], dtype=np.float64)  # Forçamos um tipo de dado em particular

print (x.dtype, y.dtype, z.dtype)


int64 float64 float64

In [55]:
matriz3 = np.array([[24, 76], [35, 89]], dtype=float)

In [56]:
matriz3


Out[56]:
array([[24., 76.],
       [35., 89.]])

In [57]:
matriz3.itemsize


Out[57]:
8

In [58]:
matriz3.nbytes


Out[58]:
32

In [59]:
matriz3.ndim


Out[59]:
2

In [60]:
matriz3[1,1]


Out[60]:
89.0

In [61]:
matriz3[1,1] = 100

In [62]:
matriz3


Out[62]:
array([[ 24.,  76.],
       [ 35., 100.]])

Usando o Método random() do NumPy


In [63]:
print(np.random.rand(10))


[0.02267953 0.76110319 0.48011904 0.36492054 0.36102244 0.49193096
 0.91159549 0.9381399  0.69339425 0.83263764]

In [64]:
import matplotlib.pyplot as plt
%matplotlib inline

In [65]:
import matplotlib as mat
mat.__version__


Out[65]:
'3.2.1'

In [66]:
print(np.random.rand(10))


[0.03287775 0.1590925  0.29997973 0.71633511 0.51275263 0.47357126
 0.10413555 0.56974932 0.37740481 0.51016438]

In [67]:
plt.show((plt.hist(np.random.rand(1000))))



In [68]:
print(np.random.randn(5,5))


[[-0.45230245  1.54038868  1.54083346  1.20460328 -1.4204455 ]
 [-0.17550676  1.30195662 -3.26491158 -1.15184384 -0.64716446]
 [ 1.18882566  1.29848752 -1.05192552  0.47594341  0.62606923]
 [ 0.83414242  1.90467968  0.78580802 -0.78434866  0.00346547]
 [ 0.34252429  0.530055   -1.38859936  0.01497015  0.52699363]]

In [69]:
plt.show(plt.hist(np.random.randn(1000)))



In [70]:
imagem = np.random.rand(30, 30)
plt.imshow(imagem, cmap = plt.cm.hot)    
plt.colorbar()


Out[70]:
<matplotlib.colorbar.Colorbar at 0x7fb99893c4d0>

Operações com datasets


In [71]:
import os
filename = os.path.join('iris.csv')

In [72]:
# No Windows use !more iris.csv. Mac ou Linux use !head iris.csv
!head iris.csv
#!more iris.csv


sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
5,3.6,1.4,0.2,setosa
5.4,3.9,1.7,0.4,setosa
4.6,3.4,1.4,0.3,setosa
5,3.4,1.5,0.2,setosa
4.4,2.9,1.4,0.2,setosa

In [73]:
# Carregando um dataset para dentro de um array
arquivo = np.loadtxt(filename, delimiter=',', usecols=(0,1,2,3), skiprows=1)
print (arquivo)


[[5.1 3.5 1.4 0.2]
 [4.9 3.  1.4 0.2]
 [4.7 3.2 1.3 0.2]
 [4.6 3.1 1.5 0.2]
 [5.  3.6 1.4 0.2]
 [5.4 3.9 1.7 0.4]
 [4.6 3.4 1.4 0.3]
 [5.  3.4 1.5 0.2]
 [4.4 2.9 1.4 0.2]
 [4.9 3.1 1.5 0.1]
 [5.4 3.7 1.5 0.2]
 [4.8 3.4 1.6 0.2]
 [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 2.8 6.7 2. ]
 [6.3 2.7 4.9 1.8]
 [6.7 3.3 5.7 2.1]
 [7.2 3.2 6.  1.8]
 [6.2 2.8 4.8 1.8]
 [6.1 3.  4.9 1.8]
 [6.4 2.8 5.6 2.1]
 [7.2 3.  5.8 1.6]
 [7.4 2.8 6.1 1.9]
 [7.9 3.8 6.4 2. ]
 [6.4 2.8 5.6 2.2]
 [6.3 2.8 5.1 1.5]
 [6.1 2.6 5.6 1.4]
 [7.7 3.  6.1 2.3]
 [6.3 3.4 5.6 2.4]
 [6.4 3.1 5.5 1.8]
 [6.  3.  4.8 1.8]
 [6.9 3.1 5.4 2.1]
 [6.7 3.1 5.6 2.4]
 [6.9 3.1 5.1 2.3]
 [5.8 2.7 5.1 1.9]
 [6.8 3.2 5.9 2.3]
 [6.7 3.3 5.7 2.5]
 [6.7 3.  5.2 2.3]
 [6.3 2.5 5.  1.9]
 [6.5 3.  5.2 2. ]
 [6.2 3.4 5.4 2.3]
 [5.9 3.  5.1 1.8]]

In [74]:
type(arquivo)


Out[74]:
numpy.ndarray

In [75]:
# Gerando um plot a partir de um arquivo usando o NumPy
var1, var2 = np.loadtxt(filename, delimiter=',', usecols=(0,1), skiprows=1, unpack=True)
plt.show(plt.plot(var1, var2, 'o', markersize=8, alpha=0.75))


Estatística


In [76]:
# Criando um array
A = np.array([15, 23, 63, 94, 75])

In [77]:
# Em estatística a média é o valor que aponta para onde mais se concentram os dados de uma distribuição.
np.mean(A)


Out[77]:
54.0

In [78]:
# O desvio padrão mostra o quanto de variação ou "dispersão" existe em 
# relação à média (ou valor esperado). 
# Um baixo desvio padrão indica que os dados tendem a estar próximos da média.
# Um desvio padrão alto indica que os dados estão espalhados por uma gama de valores.
np.std(A)


Out[78]:
30.34468652004828

In [79]:
# Variância de uma variável aleatória é uma medida da sua dispersão 
# estatística, indicando "o quão longe" em geral os seus valores se 
# encontram do valor esperado
np.var(A)


Out[79]:
920.8

In [80]:
d = np.arange(1, 10)

In [81]:
d


Out[81]:
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

In [82]:
np.sum(d)


Out[82]:
45

In [83]:
# Retorna o produto dos elementos
np.prod(d)


Out[83]:
362880

In [84]:
# Soma acumulada dos elementos
np.cumsum(d)


Out[84]:
array([ 1,  3,  6, 10, 15, 21, 28, 36, 45])

In [85]:
a = np.random.randn(400,2)
m = a.mean(0)
print (m, m.shape)


[-0.02938165 -0.02636818] (2,)

In [86]:
plt.plot(a[:,0], a[:,1], 'o', markersize=5, alpha=0.50)
plt.plot(m[0], m[1], 'ro', markersize=10)
plt.show()


Outras Operações com Arrays


In [87]:
# Slicing
a = np.diag(np.arange(3))

In [88]:
a


Out[88]:
array([[0, 0, 0],
       [0, 1, 0],
       [0, 0, 2]])

In [89]:
a[1, 1]


Out[89]:
1

In [90]:
a[1]


Out[90]:
array([0, 1, 0])

In [91]:
b = np.arange(10)

In [92]:
b


Out[92]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [93]:
# [start:end:step]
b[2:9:3]


Out[93]:
array([2, 5, 8])

In [94]:
# Comparação
a = np.array([1, 2, 3, 4])
b = np.array([4, 2, 2, 4])
a == b


Out[94]:
array([False,  True, False,  True])

In [95]:
np.array_equal(a, b)


Out[95]:
False

In [96]:
a.min()


Out[96]:
1

In [97]:
a.max()


Out[97]:
4

In [98]:
# Somando um elemento ao array
np.array([1, 2, 3]) + 1.5


Out[98]:
array([2.5, 3.5, 4.5])

In [99]:
# Usando o método around
a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5])

In [100]:
b = np.around(a)

In [101]:
b


Out[101]:
array([1., 2., 2., 2., 4., 4.])

In [102]:
# Criando um array
B = np.array([1, 2, 3, 4])

In [103]:
B


Out[103]:
array([1, 2, 3, 4])

In [104]:
# Copiando um array
C = B.flatten()

In [105]:
C


Out[105]:
array([1, 2, 3, 4])

In [106]:
# Criando um array
v = np.array([1, 2, 3])

In [107]:
# Adcionando uma dimensão ao array
v[:, np.newaxis], v[:,np.newaxis].shape, v[np.newaxis,:].shape


Out[107]:
(array([[1],
        [2],
        [3]]),
 (3, 1),
 (1, 3))

In [108]:
# Repetindo os elementos de um array
np.repeat(v, 3)


Out[108]:
array([1, 1, 1, 2, 2, 2, 3, 3, 3])

In [109]:
# Repetindo os elementos de um array
np.tile(v, 3)


Out[109]:
array([1, 2, 3, 1, 2, 3, 1, 2, 3])

In [110]:
# Criando um array
w = np.array([5, 6])

In [111]:
# Concatenando
np.concatenate((v, w), axis=0)


Out[111]:
array([1, 2, 3, 5, 6])

In [112]:
# Copiando arrays
r = np.copy(v)

In [113]:
r


Out[113]:
array([1, 2, 3])

Conheça a Formação Cientista de Dados, um programa completo, 100% online e 100% em português, com mais de 400 horas de carga horária, mais de 1.200 aulas em vídeos e 26 projetos, que vão ajudá-lo a se tornar um dos profissionais mais cobiçados do mercado de análise de dados. Clique no link abaixo, faça sua inscrição, comece hoje mesmo e aumente sua empregabilidade:

https://www.datascienceacademy.com.br/pages/formacao-cientista-de-dados

Fim

Obrigado - Data Science Academy - facebook.com/dsacademybr