Installation

    pip install numpy

    Usage

    NumPy is the core library for working with numbers in python. It provides high-performance multidimensional arrays. See full documentation.

    import numpy as np

    Input and output

    Read or write files with different formats.

    Read

    np.load('name.npy')
    np.loadtxt('name.txt')
    np.genfromtext('name.csv', delimiter=',')

    Write

    np.save('name', a)
    np.savez('name', a, b)
    np.savetxt('name.txt', a, delimiter=' ')

    Create arrays

    Different routines for creating an array. See documentation.

    a = np.array([1,2,3])
    a = np.array([[(1,2,3), (4,5,6)], [(7,8,9), (10,11,12)]], dtype=float)

    Zeros

    >>> np.zeros((2, 1))
    array([[ 0.],
           [ 0.]])

    Ones

    >>> np.ones((2, 1))
    array([[1.],
           [1.]])

    Empty

    >>> np.empty([2, 2], dtype=int)
    array([[-2312341235, -234123552],
           [  12344234,    45357345]])

    Arange

    >>> np.arange(3,7)
    array([3, 4, 5, 6])
    
    >>> np.arange(3,7,2)
    array([3, 5])

    Linspace

    >>> np.linspace(2.0, 3.0, num=5)
    array([2.  , 2.25, 2.5 , 2.75, 3.  ])

    Full

    >>> np.full((2, 2), 10)
    array([[10, 10],
           [10, 10]])

    Eye (identity)

    >>> np.eye(2, dtype=int)
    array([[1, 0],
           [0, 1]])
    
    >>> np.eye(3, k=1)
    array([[0.,  1.,  0.],
           [0.,  0.,  1.],
           [0.,  0.,  0.]])

    Describe

    # dimension
    a.shape
    
    # length
    len(a)
    
    # number of array dimensions
    a.ndim
    
    # number of array elements
    a.size
    
    # data type
    a.dtype

    Common functions

    # summation
    a.sum()
    
    # min
    a.min()
    
    # max
    a.max()
    
    # mean value
    a.mean()
    
    # median
    a.median()

    Manipulation

    Different functions for reshaping the array. See documentation

    Trasposing

    np.transpose(a)
    # or
    a.T

    Adding or removing elements

    # insert value at index
    np.insert(a, index, value)
    
    # append items
    np.append(a, b)
    
    # remove items
    np.remove(a, [1])
    
    # resize array
    a=np.array([[0,1],[2,3]])
    
    >>> np.resize(a,(2,3))
    array([[0, 1, 2],
           [3, 0, 1]])
    
    >>> np.resize(a,(1,4))
    array([[0, 1, 2, 3]])
    
    >>> np.resize(a,(2,4))
    array([[0, 1, 2, 3],
           [0, 1, 2, 3]])