Skip to content

    Chapter 5, Basic

    Creating arrays

    Every array is born in two ways: from data you already have, or generated on the fly, with the shape you request. NumPy has a function for almost every situation.

    Code for this chapter: básico/cap05_criando_arrays.py

    From your data

    The np.array converts lists (and lists of lists) into an array. Nested lists become dimensions:

    básico/cap05_criando_arrays.pylinhas 10 a 13
    import numpy as np
    
    print(np.array([1, 2, 3]))
    print(np.array([[1, 2], [3, 4]]))
    
    Output
    [1 2 3]
    [[1 2]
     [3 4]]
    

    All rows need to be the same size. An array is a rectangular grid, and NumPy refuses an "irregular" structure instead of guessing what you meant:

    básico/cap05_criando_arrays.pylinhas 15 a 18
    try:
        np.array([[1, 2], [3]])
    except ValueError as erro:
        print("erro de forma irregular:", "inhomogeneous" in str(erro))
    
    Output
    erro de forma irregular: True
    

    Filling arrays: you provide the shape

    When you don't have the values yet, but know the shape, fill arrays reserve the space. The shape is a tuple, and that’s where the most common mistake lies:

    básico/cap05_criando_arrays.pylinhas 23 a 25
    print(np.zeros((2, 3)))
    print(np.ones((2, 3), dtype=int))
    print(np.full((2, 3), 7))
    
    Output
    [[0. 0. 0.]
     [0. 0. 0.]]
    [[1 1 1]
     [1 1 1]]
    [[7 7 7]
     [7 7 7]]
    
    básico/cap05_criando_arrays.pylinhas 27 a 30
    try:
        np.zeros(2, 3)
    except TypeError as erro:
        print(erro)
    
    Output
    Cannot interpret '3' as a data type
    

    Writing np.zeros(2, 3), NumPy understands the 3 as the data type (the second parameter), and that’s why the message refers to "data type". The form is a single argument: np.zeros((2, 3)), with double parentheses.

    The np.empty also reserves the form, but does not initialize the memory: the content is what was already there, not zero. It is a bit faster than the zeros, and only serves when you are going to overwrite all the values right after. I rarely use it because the gain is small and the risk of reading garbage is real.

    Special matrices

    básico/cap05_criando_arrays.pylinhas 35 a 36
    print(np.eye(3))
    print(np.diag([1, 2, 3]))
    
    Output
    [[1. 0. 0.]
     [0. 1. 0.]
     [0. 0. 1.]]
    [[1 0 0]
     [0 2 0]
     [0 0 3]]
    

    The np.eye(3) is the identity matrix (ones on the diagonal). The np.diag builds a diagonal matrix from a list, and if it receives a matrix, it does the reverse and extracts the diagonal.

    Sequences

    básico/cap05_criando_arrays.pylinhas 41 a 43
    print(np.arange(0, 10, 2))
    print(np.linspace(0, 1, 5))
    print(np.logspace(0, 2, 3))
    
    Output
    [0 2 4 6 8]
    [0.   0.25 0.5  0.75 1.  ]
    [  1.  10. 100.]
    

    The arange works like the range of Python: start, end (excluded), and step. The linspace receives the number of points and includes both extremes. The logspace spaces the points on a logarithmic scale, from 10⁰ to 10², three points.

    arange with decimal step

    With decimal steps, the arange accumulates floating-point error and can surprise you with the size of the result. When you know how many points you want, the linspace is more predictable:

    básico/cap05_criando_arrays.pylinha 45
    print(len(np.arange(0, 1, 0.1)), len(np.linspace(0, 1, 11)))
    
    Output
    10 11
    

    The arange produces 10 points and excludes 1. The linspace(0, 1, 11) produces 11 and includes both extremes. When in doubt, use linspace.

    Arrays in the shape of another

    The functions *_like create an array with the same shape (and the same type, unless you say otherwise) as an existing array:

    básico/cap05_criando_arrays.pylinhas 50 a 52
    base = np.array([[1, 2, 3], [4, 5, 6]])
    print(np.zeros_like(base))
    print(np.ones_like(base, dtype=float).shape)
    
    Output
    [[0 0 0]
     [0 0 0]]
    (2, 3)
    

    Chapter 16 introduces random arrays, which are also a form of creation.

    Exercise 1

    Multiples and constant matrices

    Write multiplos_de(passo, limite) that returns the multiples of passo from 0 to limite (inclusive), and matriz_constante(linhas, colunas, valor).