Numpy Array (ndarray) Examples

Numpy Array (ndarray) Examples

Last updated:
Table of Contents

Examples use numpy v.14.5 unless specified

See online at queirozfcom/python-sandbox

Copy array by value

use .copy()

import numpy as np

x = np.array([
    [1,2,3],
    [4,5,6]
])

y = x.copy()

# fill y with 1's
y.fill(1)

# x is unchanged
x
# array([[1, 2, 3],
#        [4, 5, 6]])

y 
# array([[1, 1, 1],
#        [1, 1, 1]])

Access row/column of multidimensional array

Keep in mind: 0 means rows, 1 means columns, : means everything in that dimension

import numpy as np

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

# select all rows for column 1
myarray[:,1]
# array([2, 5, 8])

# select all columns for row 0
myarray[0,:]
# array([1, 2, 3])

Build matrix from list of ndarrays

This is useful if you want to build a matrix row by row.

import numpy as np

lst = []

lst.append(np.array([1,2,3]))
lst.append(np.array([4,4,4]))

# vstack stands for "vertical stacking"
matrix = np.vstack(lst)

print(matrix)
# array([[1, 2, 3],
#        [4, 4, 4]])

print(matrix.shape)
# (2,3)

Reverse array

Use the [::-1] notation:

import numpy as np

myarray = np.array([1,2,3])
myarray[::-1]
# array([3, 2, 1])

it also works for higher dimensions:

myarray = np.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])
myarray[::-1]
# array([[7, 8, 9],
#       [4, 5, 6],
#       [1, 2, 3]])

You can also use np.flip()

Add row to array

Use np.vstack([array1,array2]) to add a row to a multimensional ndarray.

Vstack means vertical stacking.

import numpy as np

myarray = np.array([
    [1,2,3],
    [4,5,6]
])

newrow = np.array([9,9,9])

np.vstack([myarray,newrow])
# array([[1, 2, 3],
#       [4, 5, 6],
#       [9, 9, 9]])

Add column to array

np.hstack([array1, array2]) means horizontal stacking:

import numpy as np

myarray = np.array([
    [1,2,3],
    [4,5,6]
])

newcol = np.array([[9],[9]])

np.hstack([myarray,newcol])
# array([[1, 2, 3, 9],
#        [4, 5, 6, 9]])

Compare two arrays for equality

For approximate matches, use np.allclose() instead

np.array_equal(a,b) returns True is all elements from a and b are strictly equal to one another (element-wise)

import numpy as np

a = np.array([1,2,3])
b = np.array([0,0,0])

np.array_equal(a,b)
# False

Heads up! np.array_equal will return False if either array has NaNs!

import numpy as np

a = np.array([1,np.nan,3])
b = np.array([1,np.nan,3])

# nan is not equal to anything, not even itself
np.array_equal(a,b)
# False

Compare arrays with NaNs

Using array_equal(a,b) will always return False for any arrays containing nan.

Use allclose(a,b,equal_nan=True) to compare arrays with nan.

import python as np

a = np.array([1,np.nan,3])
b = np.array([1,np.nan,3])

np.array_equal(a,b)
# >>> False

np.allclose(a,b,equal_nan=True)
# >>> True
import numpy as np

np.set_printoptions(threshold=np.inf)

To reset the original print options, call set_printoptions() with the default arguments

Use np.set_printoptions(suppress=True)

import python as np

np.set_printoptions(suppress=True)
np.array([1.0e-10,1.0,100,1000])

default-numpy-print-options BEFORE: default print options
         
modified-numpy-print-options AFTER setting print options

Reset print options

To reset the original print options, call np.set_printoptions() with the default arguments:

import numpy as np

np.set_printoptions(edgeitems=3,infstr='inf',
linewidth=75, nanstr='nan', precision=8,
suppress=False, threshold=1000, formatter=None)

array to column vector

(-1,1) means as many rows as needed an 1 column

Make a NxM ndarray become a one-dimensional array with N*M rows (and 1 column)

Use reshape(-1,1):

import python as np

arr = np.array([
    [1,2,3],
    [4,5,6]    
])
# >>> array([[1, 2, 3],
#            [4, 5, 6]])

arr.reshape(-1,1)
# >>> array([[1],
#            [2],
#            [3],
#            [4],
#            [5],
#            [6]])

array to row vector

(1,-1) means as many 1 row and as many columns as neded

Make a NxM ndarray become a one-dimensional array with N*M columns (and 1 row).

Use reshape(1,-1):

import python as np

arr = np.array([
    [1,2,3],
    [4,5,6]    
])
# >>> array([[1, 2, 3],
#            [4, 5, 6]])

arr.reshape(1,-1)
# >>> array([[1, 2, 3, 4, 5, 6]])

Dialogue & Discussion