Table of Contents

Reference

For more details, see numpy official api reference.

Preparation

pip install -U pip
pip install numpy

Creation methods

A n-dimensional array (ndarray) is the most important and basic class in numpy. It has a constructor but its elements will not be initialized.

# Interactive mode
python

>>> import numpy as n

>>> np.ndarray(3)
array([0.e+000, 5.e-324, 1.e-323]) # random values

# An array of 3x2
>>> np.ndarray((3, 2))
array([[0.0e+000, 4.9e-324],
       [9.9e-324, 1.5e-323],
       [2.0e-323, 2.5e-323]]) # random values

array is an useful interface to create a ndarray object. It can recieve an array object and elements will be initialized by it.

# Interactive mode
python

>>> import numpy as n

# Create an array
>>> np.array([0, 1, 2])
array([0, 1, 2])

# An array of 2x3
>>> np.array([[0, 1, 2], [3, 4, 5]])
array([[0, 1, 2],
       [3, 4, 5]])

# Type provided
>>> np.array([0, 1, 2], dtype=float)
array([0., 1., 2.])

zeros, ones, full are also aften used.

zeros:

# Interactive mode
python

>>> import numpy as n

# Create an array of zeros
# Default dtype is numpy.float64
>>> np.zeros(2)
array([0., 0.])

# Type provided
>>> np.zeros((2, 3), dtype=int)
array([[0, 0, 0],
       [0, 0, 0]])

ones:

# Create an array of zeros
# Default dtype is numpy.float64
>>> np.ones(2)
array([1., 1.])

# Type provided
>>> np.ones((2, 3), dtype=np.int8)
array([[1, 1, 1],
       [1, 1, 1]], dtype=int8)

full:

# Create an array filled with given value
>>> np.full(2, 100)
array([100, 100])

>>> np.full((2, 3), np.inf)
array([[inf, inf, inf],
       [inf, inf, inf]])

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

array_like interfaces (zeros_like, ones_like and full_like) create an array with the same shape and type as a given array.

zeros_like:

# Interactive mode
python

>>> import numpy as n

>>> a = np.array([0, 1, 2], dtype=np.float64)
>>> a
array([0., 1., 2.])

>>> a.dtype
dtype('float64')



>>> np.zeros_like(a)
array([0., 0., 0.])

>>> np.zeros_like(a).dtype
dtype('float64')

ones_like:

>>> np.ones_like(a)
array([1., 1., 1.])

>>> np.ones_like(a).dtype
dtype('float64')

full_like:

>>> np.full_like(a, 100)
array([100., 100., 100.])

>>> np.full_like(a, 100).dtype
dtype('float64')