Numpy Tutorial PDF
Numpy Tutorial PDF
This tutorial explains the basics of NumPy such as its architecture and environment. It also
discusses the various array functions, types of indexing, etc. An introduction to Matplotlib
is also provided. All this is explained with the help of examples for better understanding.
Audience
This tutorial has been prepared for those who want to learn about the basics and various
functions of NumPy. It is specifically useful for algorithm developers. After completing this
tutorial, you will find yourself at a moderate level of expertise from where you can take
yourself to higher levels of expertise.
Prerequisites
You should have a basic understanding of computer programming terminologies. A basic
understanding of Python and any of the programming languages is a plus.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
i
NumPy
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
ndarray.shape ....................................................................................................................................... 12
ndarray.ndim ........................................................................................................................................ 13
numpy.itemsize ..................................................................................................................................... 14
numpy.flags .......................................................................................................................................... 14
numpy.empty........................................................................................................................................ 16
numpy.zeros ......................................................................................................................................... 17
numpy.ones .......................................................................................................................................... 18
numpy.asarray ...................................................................................................................................... 19
numpy.frombuffer ................................................................................................................................ 20
ii
NumPy
numpy.fromiter..................................................................................................................................... 21
numpy.arange ....................................................................................................................................... 23
numpy.linspace ..................................................................................................................................... 24
numpy.logspace .................................................................................................................................... 25
numpy.reshape ..................................................................................................................................... 47
numpy.ndarray.flat ............................................................................................................................... 48
numpy.ndarray.flatten .......................................................................................................................... 48
numpy.ravel .......................................................................................................................................... 49
numpy.transpose .................................................................................................................................. 50
numpy.ndarray.T................................................................................................................................... 51
numpy.swapaxes .................................................................................................................................. 52
numpy.rollaxis ...................................................................................................................................... 53
numpy.broadcast .................................................................................................................................. 54
iii
NumPy
numpy.broadcast_to ............................................................................................................................. 56
numpy.expand_dims ............................................................................................................................. 57
numpy.squeeze ..................................................................................................................................... 59
numpy.concatenate .............................................................................................................................. 60
numpy.stack .......................................................................................................................................... 61
numpy.split ........................................................................................................................................... 64
numpy.resize ......................................................................................................................................... 66
numpy.append ...................................................................................................................................... 68
numpy.insert ......................................................................................................................................... 69
numpy.delete ........................................................................................................................................ 71
numpy.unique ....................................................................................................................................... 72
bitwise_and .......................................................................................................................................... 75
bitwise_or ............................................................................................................................................. 76
numpy.invert() ...................................................................................................................................... 77
left_shift ............................................................................................................................................... 78
right_shift ............................................................................................................................................. 79
numpy.reciprocal() ................................................................................................................................ 93
iv
NumPy
numpy.power() ..................................................................................................................................... 94
numpy.mod() ........................................................................................................................................ 95
numpy.ptp() .......................................................................................................................................... 99
numpy.median().................................................................................................................................. 102
numpy.lexsort()................................................................................................................................... 110
v
NumPy
Determinant........................................................................................................................................ 130
vi
1. NUMPY − INTRODUCTION NumPy
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray
was also developed, having some additional functionalities. In 2005, Travis Oliphant created
NumPy package by incorporating the features of Numarray into Numeric package. There are
many contributors to this open source project.
7
2. NUMPY − ENVIRONMENT NumPy
Standard Python distribution doesn't come bundled with NumPy module. A lightweight
alternative is to install NumPy using popular Python package installer, pip.
The best way to enable NumPy is to use an installable binary package specific to your
operating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy,
matplotlib, IPython, SymPy and nose packages along with core Python).
Windows
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is
also available for Linux and Mac.
Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows
OS. (Downloadable from http://python-xy.github.io/)
Linux
Package managers of respective Linux distributions are used to install one or more packages
in SciPy stack.
For Ubuntu
sudo apt-get install python-numpy python-scipy python-matplotlibipythonipython-
notebook python-pandas python-sympy python-nose
For Fedora
sudo yum install numpyscipy python-matplotlibipython python-pandas sympy python-
nose atlas-devel
8
NumPy
To test whether NumPy module is properly installed, try to import it from Python prompt.
import numpy
import numpy as np
9
3. NUMPY − NDARRAY OBJECT NumPy
The most important object defined in NumPy is an N-dimensional array type called ndarray.
It describes the collection of items of the same type. Items in the collection can be accessed
using a zero-based index.
Every item in an ndarray takes the same size of block in the memory. Each element in ndarray
is an object of data-type object (called dtype).
Any item extracted from ndarray object (by slicing) is represented by a Python object of one
of array scalar types. The following diagram shows a relationship between ndarray, data type
object (dtype) and array scalar type:
An instance of ndarray class can be constructed by different array creation routines described
later in the tutorial. The basic ndarray is created using an array function in NumPy as follows:
numpy.array
It creates an ndarray from any object exposing array interface, or from any method that
returns an array.
10
NumPy
Any object exposing the array interface method returns an array, or any
object
(nested) sequence
Example 1
import numpy as np
a=np.array([1,2,3])
print a
[1, 2, 3]
Example 2
# more than one dimensions
import numpy as np
11
NumPy
[[1, 2]
[3, 4]]
Example 3
# minimum dimensions
import numpy as np
a=np.array([1, 2, 3,4,5], ndmin=2)
print a
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype=complex)
print a
12
4. NUMPY − DATA TYPES NumPy
NumPy supports a much greater variety of numerical types than Python does. The following
table shows different scalar data types defined in NumPy.
int_ Default integer type (same as C long; normally either int64 or int32)
13
NumPy
NumPy numerical types are instances of dtype (data-type) objects, each having unique
characteristics. The dtypes are available as np.bool_, np.float32, etc.
Size of data
In case of structured type, the names of fields, data type of each field and part of the
memory block taken by each field
The byte order is decided by prefixing '<' or '>' to data type. '<' means that encoding is little-
endian (least significant is stored in smallest address). '>' means that encoding is big-endian
(most significant byte is stored in smallest address).
Copy: Makes a new copy of dtype object. If false, the result is reference to built-in
data type object
Example 1
# using array-scalar type
import numpy as np
dt=np.dtype(np.int32)
print dt
int32
14
NumPy
Example 2
#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4',
etc.
import numpy as np
dt = np.dtype('i4')
print dt
int32
Example 3
# using endian notation
import numpy as np
dt = np.dtype('>i4')
print dt
>i4
The following examples show the use of structured data type. Here, the field name and the
corresponding scalar data type is to be declared.
Example 4
# first create structured data type
import numpy as np
dt = np.dtype([('age',np.int8)])
print dt
[('age', 'i1')]
Example 5
# now apply it to ndarray object
15
NumPy
import numpy as np
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype=dt)
print a
Example 6
# file name can be used to access content of age column
import numpy as np
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype=dt)
print a['age']
[10 20 30]
Example 7
The following examples define a structured data type called student with a string field 'name',
an integer field 'age' and a float field 'marks'. This dtype is applied to ndarray object.
import numpy as np
student=np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
print student
Example 8
import numpy as np
student=np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype=student)
16
NumPy
print a
Each built-in data type has a character code that uniquely identifies it.
'b': boolean
'i': (signed) integer
'u': unsigned integer
'f': floating-point
'c': complex-floating point
'm': timedelta
'M': datetime
'O': (Python) objects
'S', 'a': (byte-)string
'U': Unicode
'V': raw data (void)
17
5. NUMPY − ARRAY ATTRIBUTES NumPy
ndarray.shape
This array attribute returns a tuple consisting of array dimensions. It can also be used to
resize the array.
Example 1
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print a.shape
(2, 3)
Example 2
# this resizes the ndarray
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
a.shape=(3,2)
print a
[[1 2]
[3 4]
[5 6]]
Example 3
NumPy also provides a reshape function to resize an array.
import numpy as np
18
NumPy
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print b
[[1 2]
[3 4]
[5 6]]
ndarray.ndim
This array attribute returns the number of array dimensions.
Example 4
# an array of evenly spaced numbers
import numpy as np
a = np.arange(24)
print a
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Example 5
# this is one dimensional array
import numpy as np
a = np.arange(24)
a.ndim
# now reshape it
b = a.reshape(2,4,3)
print b
# b is having three dimensions
19
NumPy
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
numpy.itemsize
This array attribute returns the length of each element of array in bytes.
Example 6
# dtype of array is int8 (1 byte)
import numpy as np
x = np.array([1,2,3,4,5], dtype=np.int8)
print x.itemsize
Example 7
# dtype of array is now float32 (4 bytes)
import numpy as np
x = np.array([1,2,3,4,5], dtype=np.float32)
print x.itemsize
20
NumPy
numpy.flags
The ndarray object has the following attributes. Its current values are returned by this
function.
OWNDATA (O) The array owns the memory it uses or borrows it from another object
WRITEABLE (W) The data area can be written to. Setting this to False locks the data,
making it read-only
ALIGNED (A) The data and all elements are aligned appropriately for the hardware
This array is a copy of some other array. When this array is
UPDATEIFCOPY (U) deallocated, the base array will be updated with the contents of this
array
Example 8
The following example shows the current values of flags.
import numpy as np
x = np.array([1,2,3,4,5])
print x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
21
6. NUMPY − ARRAY CREATION ROUTINES NumPy
A new ndarray object can be constructed by any of the following array creation routines or
using a low-level ndarray constructor.
numpy.empty
It creates an uninitialized array of specified shape and dtype. It uses the following constructor:
Order 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
Example 1
The following code shows an example of an empty array.
import numpy as np
x = np.empty([3,2], dtype=int)
print x
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
Note: The elements in an array show random values as they are not initialized.
22
NumPy
numpy.zeros
Returns a new array of specified size, filled with zeros.
Order 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
Example 2
# array of five zeros. Default dtype is float
import numpy as np
x = np.zeros(5)
print x
[ 0. 0. 0. 0. 0.]
Example 3
import numpy as np
x = np.zeros((5,), dtype=np.int)
print x
[0 0 0 0 0]
23
NumPy
Example 4
# custom type
import numpy as np
x = np.zeros((2,2), dtype=[('x', 'i4'), ('y', 'i4')])
print x
numpy.ones
Returns a new array of specified size and type, filled with ones.
Order 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
Example 5
# array of five ones. Default dtype is float
import numpy as np
x = np.ones(5)
print x
[ 1. 1. 1. 1. 1.]
Example 6
import numpy as np
x = np.ones([2,2], dtype=int)
print x
[[1 1]
[1 1]]
25
7. NUMPY − ARRAY FROM EXISTING DATA NumPy
In this chapter, we will discuss how to create an array from existing data.
numpy.asarray
This function is similar to numpy.array except for the fact that it has fewer parameters. This
routine is useful for converting Python sequence into ndarray.
Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple
a
of lists
dtype By default, the data type of input data is applied to the resultant ndarray
The following examples show how you can use the asarray function.
Example 1
# convert list to ndarray
import numpy as np
x = [1,2,3]
a = np.asarray(x)
print a
[1 2 3]
26
NumPy
Example 2
# dtype is set
import numpy as np
x = [1,2,3]
a = np.asarray(x, dtype=float)
print a
[ 1. 2. 3.]
Example 3
# ndarray from tuple
import numpy as np
x = (1,2,3)
a = np.asarray(x)
print a
[1 2 3]
Example 4
# ndarray from list of tuples
import numpy as np
x = [(1,2,3),(4,5)]
a = np.asarray(x)
print a
27
NumPy
numpy.frombuffer
This function interprets a buffer as one-dimensional array. Any object that exposes the buffer
interface is used as parameter to return an ndarray.
Example 5
The following examples demonstrate the use of frombuffer function.
import numpy as np
s = 'Hello World'
a = np.frombuffer(s, dtype='S1')
print a
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
numpy.fromiter
This function builds an ndarray object from any iterable object. A new one-dimensional array
is returned by this function.
dtype
Data type of resultant array
28
NumPy
The number of items to be read from iterator. Default is -1 which means all data
count
to be read
The following examples show how to use the built-in range() function to return a list object.
An iterator of this list is used to form an ndarray object.
Example 6
# create list object using range function
import numpy as np
list = range(5)
print list
[0, 1, 2, 3, 4]
Example 7
# obtain iterator object from list
import numpy as np
list = range(5)
it = iter(list)
[0. 1. 2. 3. 4.]
29
8. NUMPY − ARRAY FROM NUMERICAL RANGES NumPy
In this chapter, we will see how to create an array from numerical ranges.
numpy.arange
This function returns an ndarray object containing evenly spaced values within a given range.
The format of the function is as follows:
dtype Data type of resulting ndarray. If not given, data type of input is used
The following examples show how you can use this function.
Example 1
import numpy as np
x = np.arange(5)
print x
[0 1 2 3 4]
30
NumPy
Example 2
import numpy as np
# dtype set
x = np.arange(5, dtype=float)
print x
[0. 1. 2. 3. 4.]
Example 3
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x
[10 12 14 16 18]
numpy.linspace
This function is similar to arange() function. In this function, instead of step size, the number
of evenly spaced values between the interval is specified. The usage of this function is as
follows:
stop The end value of the sequence, included in the sequence if endpoint set to true
31
NumPy
True by default, hence the stop value is included in the sequence. If false, it is not
endpoint
included
retstep If true, returns samples and step between the consecutive numbers
32
NumPy
33