Getting Started with Python Library Numpy

NumPy is a open source Python library that handles multidimensional arrays and matrices with a huge library of mathematical functions to manipulate arrays. If you are working with image processing, voice processing or machine learning, Learning NumPy should greatly improve your research and development.

NumPy makes it easy to work with data in the formats required for machine learning , such as vectors and matrices .

How to install NumPy

NumPy is open source and can be build from its source code. You can also use pip to install NumPy.

To install NumPy on Linux using pip, run the following command on terminal:

sudo pip3 install numpy

To install NumPy on WIndows using pop, run the following command on command prompt. Make sure you have installed pip before you run the command to install NumPy

pip3 install numpy

The main NumPy object is a homogeneous multidimensional array (called numpy.ndarray in numpy). It is a multidimensional array of elements (usually numbers) of the same type.

The most important attributes of ndarray objects are:

  • ndarray.ndim is the number of dimensions (more often called “axes”) of the array.
  • ndarray.shape is the size of the array. It is a tuple of natural numbers showing the length of the array along each axis. For a matrix of n rows and m columns, shape would be (n, m). The number of elements of the shape tuple is ndim.
  • ndarray.size is the number of elements in the array which is n*m from the array shape.
  • ndarray.dtype is an object describing the type of array elements. You can define dtype using standard Python data types. NumPy here provides a whole bunch of possibilities, both built-in, for example: bool_, character, int8, int16, int32, int64, float8, float16, float32, float64, complex64, object_, and the ability to define your own data types, including composite ones.
  • ndarray.itemsize is the size of each element in the array in bytes.
  • ndarray.data is a buffer containing the actual elements of the array. Usually this attribute is not used much as the easiest way to access array elements is using indices.

Also read:

How to create an array in NumPy

There are many ways to create an array in NumPy. One of the simpler ones is to create an array from regular Python lists or tuples using the numpy.array() function:

import numpy
numpy.array([1,2])
# result: array([1, 2])

To create multidimensional arrays in NumPy, just use multidimensional list in array function

import numpy
numpy.array([[1,2],[3,4]])
# result: array([[1, 2],
#                 [3, 4]])

array() function is not the only function that creates array in NumPy, If you want to create an array and initialize the content to ‘0’, you can use zeros() function. Similarly there are other functions like ones to initialize the array content to 1, eye () function to create an identity matrix, empty() function to create empty array with random numbers assigned, arange() to create a sequence of numbers.

import numpy
numpy.zeros((2,2))
# result: array([[ 0.,  0.],
#                [ 0.,  0.]])

numpy.ones((2,2))
# result: array([[ 1.,  1.],
#                [ 1.,  1.]])

numpy.eye((2))
# result: array([[ 1.,  0.],
                 [ 0.,  1.]])

numpy.empty((2,2))
# result: array([[  3.10503618e+231,   3.10503618e+231],
                 [  4.22764506e-307,   0.00000000e+000]])

numpy.arange(20,50,  5)
# result: array([20, 25, 30, 35, 40, 45])

Check the Element datatype in NumPy Array

Arrays in NumPy cannot mix element types. Use the dtype property to see the type of the element.

import numpy
p = numpy.arange(20,50,  5)
p.dtype
# result: dtype('int64')

Use the shape property to examine the structure of the array.

import numpy
p = numpy.arange(20,50,  5)
p.shape
# result: (6,)

Use the size property to find out the total number of elements.

import numpy
p = numpy.arange(20,50,  5)
p.size
# result: 6

add an element in NumPy array

Use the append function to add an element in NumPy array. Use the insert function to insertion and the delete function to delete an element in an array.

When adding an element to a multidimensional array, specify axis = 0 to add a row and axis = 1 to add a column.

import numpy
p = numpy.append(p,1) # append 1 at the end of the array
p = numpy.insert(p,0,12) # insert 12 at index 0
p = numpy.delete(p,0) # remove element at index 0

convert the array dimensions in NumPy Array

Use the reshape function to transform the dimensions of an array, such as turning a one-dimensional array into a two-dimensional array. If -1 is specified for the number of elements, it will be calculated automatically from the number of elements in other dimensions.

import numpy
p = numpy.array([20, 25, 30, 35, 40, 45])
print(p)
p = p.reshape(2,-1)
print(p)

# result: [20 25 30 35 40 45]
# result: [[20 25 30]
           [35 40 45]]

Access the elements of the NumPy Array

NumPy arrays can be accessed by index number, just like Python lists.

import numpy
p = numpy.array([20, 25, 30, 35, 40, 45])
print(p)
print(p[:2])

# result: [20  25  30  35  40  45]
# result: [[20 25  30] 
           [35  40  45]]

You can also extract it with a conditional expression, just like a Python list.

import numpy
x = numpy.array (range (1, 5))
print (x)
print (x [x> 2])

# result: [1 2 3 4]
# result [3 4]

Generate an evenly spaced sequence in numPy

Use the linspace() function to generate an evenly spaced sequence.

import numpy
numpy.linspace (0, 2, num = 10)
array([ 0.        ,  0.22222222,  0.44444444,  0.66666667,  0.88888889,
        1.11111111,  1.33333333,  1.55555556,  1.77777778,  2.        ])

Generate random numbers in NumPy

To generate a random number in NumPy, use the random.rand or random.randn function. rand produces uniform random numbers and randn produces standard normally distributed random numbers.

import numpy
numpy.random.rand (5, 1)
array([[ 0.29867417],
       [ 0.49081114],
       [ 0.10096043],
       [ 0.04049271],
       [ 0.95827299]])

Mix the elements of the array in numPy

Use the shuffle function to mix the elements of an array.

import numpy
p = numpy.array(range(1,5))
print(p)
# result: [1 2 3 4]

numpy.random.shuffle(p)
print(p)
# result: [4 2 3 1]

Sort an array in NumPy

To sort the elements of an array in NumPy, use the sort function.

import numpy
p = numpy.array(range(1,5))
numpy.random.shuffle(p)
print (p)
# result: [1 4 3 2]

p = numpy.sort(p)
print(p)
#result: [1 2 3 4]

How to sort in descending order. Since the sort command does not have an option to sort in descending order, it can be achieved by extracting the sorted results in order from the back.

import numpy
p = numpy.array(range(1,5))
numpy.random.shuffle(p)
print (p)
# result: [1 4 3 2]

p = numpy.sort(p)[:: -1]
print(p)
#result: [4 3 2 1]

Join arrays together in NumPy

Use the vstack instruction to join arrays together.

>>> a = numpy.array([2,3,4])
>>> b = numpy.array([5,6,7])
>>> c = numpy.vstack((a,b))
>>> print (c)
[[2 3 4]
 [5 6 7]]

Download PDF tutorial for NumPy: here.

Scroll to Top