Skip to main content
Numpy

Numpy #

Warning: This post hasn't been updated for over a year. The information may be out of date.

(Maybe) Useful resources #

Create full arrays #

Speed test: python - Create numpy matrix filled with NaNs - Stack Overflow

fill #

Make array of fixed dimensions, then fill it with something.

np.full((2,5), np.nan)
# array([[nan, nan, nan, nan, nan],
#        [nan, nan, nan, nan, nan]])

np.full((2,5), [0, 1])
# ValueError: could not broadcast input array from shape (2,) into shape (2,5)

np.full((2,5), [[0],[1]])
# array([[0, 0, 0, 0, 0],
#        [1, 1, 1, 1, 1]])

tile #

Repeating the same input array by given times.

np.tile(np.nan, (2, 5))
# array([[nan, nan, nan, nan, nan],
#        [nan, nan, nan, nan, nan]])

np.tile([0, 1], (2,5))
# array([[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
#        [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]])

np.tile([[0],[1]], (2,5))
# array([[0, 0, 0, 0, 0],
#        [1, 1, 1, 1, 1],
#        [0, 0, 0, 0, 0],
#        [1, 1, 1, 1, 1]])

reshape #

Take any list or array, and rearrange the elements into given shape (dimensions).

Make array of 1 ~ 100:

np.arange(1, 101).reshape(10, 10)
# array([[  1,   2,   3,   4,   5,   6,   7,   8,   9,  10],
#        [ 11,  12,  13,  14,  15,  16,  17,  18,  19,  20],
#        [ 21,  22,  23,  24,  25,  26,  27,  28,  29,  30],
#        [ 31,  32,  33,  34,  35,  36,  37,  38,  39,  40],
#        [ 41,  42,  43,  44,  45,  46,  47,  48,  49,  50],
#        [ 51,  52,  53,  54,  55,  56,  57,  58,  59,  60],
#        [ 61,  62,  63,  64,  65,  66,  67,  68,  69,  70],
#        [ 71,  72,  73,  74,  75,  76,  77,  78,  79,  80],
#        [ 81,  82,  83,  84,  85,  86,  87,  88,  89,  90],
#        [ 91,  92,  93,  94,  95,  96,  97,  98,  99, 100]])

Make array out of arbitrary numbers: (taken from here, a positive definite matrix)

np.reshape((2, -1, 0, -1, 2, -1, 0, -1, 2), (3, 3))
# array([[ 2, -1,  0],
#        [-1,  2, -1],
#        [ 0, -1,  2]])

Create diagonal arrays #

diag #

Make diagonal matrix. (ref)

np.diagflat([-1] * 3)
# array([[-1,  0,  0],
#        [ 0, -1,  0],
#        [ 0,  0, -1]])

np.diagflat([[-1]] * 3)
# array([[-1,  0,  0],
#        [ 0, -1,  0],
#        [ 0,  0, -1]])

diagflat #

Make diagonal matrix, or extract the diagonal, according to dimensions of input.

np.diag([-1] * 3)
# array([[-1,  0,  0],
#        [ 0, -1,  0],
#        [ 0,  0, -1]])

np.diag([[-1]] * 3)
# array([-1])

A = np.arange(1, 10).reshape(3,3)

np.diag(A)
# array([1, 5, 9])

np.diag(np.diag(A))
# array([[1, 0, 0],
#        [0, 5, 0],
#        [0, 0, 9]])

Create triangular arrays #

triu_indices #

Create upper triangular array out of lists: (ref)

import numpy as np

def create_triu(values, size):
    upper = np.zeros((size, size))
    upper[np.triu_indices(3, 0)] = values
    return(upper)

create_triu([1, 2, 3, 4, 5, 6], size=3)
# array([[1, 2, 3],
#        [0, 4, 5],
#        [0, 0, 6]], dtype=uint8)