Wednesday 4 January 2017

How do we create a Numpy array?

Numpy has built-in functions for creating arrays.

zeros(shape) will create an array filled with "0" values with the specified shape. The default dtype is float64.
Example:
>>> np.zeros((2, 3))
array([[ 0.,  0.,  0.],

       [ 0.,  0.,  0.]])

ones(shape) will create an array filled with 1 values.
Example:
>>> np.ones((2,3))
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

arange() will create arrays with regular increment values
Example:
>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> np.arange(2, 10, dtype=np.float)
array([ 2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])


>>> np.arange(2, 3, 0.1)
array([ 2. ,  2.1,  2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9])

linspace() will create arrays with a specified number of elements, and spaced equally between the specified beginning and end values.
Example:
>>> np.linspace(1., 4., 6)
array([ 1. ,  1.6,  2.2,  2.8,  3.4,  4. ])

indices() will create a set of arrays (stacked as a one-higher dimensioned array), one per dimension with each representing variation in that dimension.
Example:
>>> np.indices((3,3))
array([[[0, 0, 0],
        [1, 1, 1],
        [2, 2, 2]],

       [[0, 1, 2],
        [0, 1, 2],
        [0, 1, 2]]])