Numpy

Using NumPy

After install NumPy, import it as a library:

import numpy as np

Creating NumPy Arrays

From a Python List

my_list = [1,2,3]
np.array(my_list)

my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
np.array(my_matrix)

Built-in Methods

np.zeros((5,5)) : Generate arrays of zeros
np.ones((3,3)) : Generate arrays of ones
np.eye(4) : Creates an identity matrix

  1. arange
    Return evenly spaced values within a given interval.

    np.arange(0,10)
    >> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    np.arange(0,11,2)
    >> array([ 0, 2, 4, 6, 8, 10])
  2. linspace
    Return evenly spaced numbers over a specified interval.

    np.linspace(0,10,5)
    >> array([ 0. , 2.5, 5. , 7.5, 10. ])

    Note: arange 和 linspace不同:arange是給每個數的間隔,linspace是給有多少個數

  3. random

  • rand
    Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

    np.random.rand(2,2)
    >> array([[0.64065034, 0.16643695],
    [0.5944612 , 0.96361622]])
  • randn
    Return a sample (or samples) from the “standard normal” distribution over.

    np.random.randn(2,2)
    >> array([[-0.10332894, 0.12954978],
    [ 0.535127 , -2.51244816]])
  • randint
    Return random integers from low (inclusive) to high (exclusive).

    np.random.randint(1,100,10)
    >> array([13, 64, 27, 63, 46, 68, 92, 10, 58, 24])
  1. reshape
    Returns an array containing the same data with a new shape.
    arr = np.arange(25)
    arr.reshape(5,5)
    >> array([[ 0, 1, 2, 3, 4],
    [ 5, 6, 7, 8, 9],
    [10, 11, 12, 13, 14],
    [15, 16, 17, 18, 19],
    [20, 21, 22, 23, 24]])

Attributes

  1. shape
    Shape is an attribute that arrays have.

    arr = np.arange(4)
    arr.shape
    >> (4,) #vector
    arr.reshape(1,4).shape
    >> (1, 4)
  2. dtype
    Use dtype to grab the data type of the object in the array.

    arr.dtype
    >> dtype('int64')

NumPy Indexing and Selection

NumPy Indexing and Selection

The simplest way to pick one or some elements of an array looks very similar to python lists:

arr.dtype
>> dtype('int64')