Department of Computer Science and Engineering
Python – NumPy Lab Manual
Branch: CSE Year & Sem: II –I
Experiment No: 1
NumPy Installation using different scientific python
distribution (Anaconda, Python(x,y), WinPython, Pyzo)
Installation
These are general instructions for installing packages in the SciPy ecosystem.
Scientific Python distributions
For many users, especially on Windows, the easiest way to begin is to download one
of these Python distributions, which include all the key packages:
Anaconda: A free distribution of Python with scientific packages. Supports
Linux, Windows and Mac.
Enthought Canopy: The free and commercial versions include the core
scientific packages. Supports Linux, Windows and Mac.
Python(x,y): A free distribution including scientific packages, based around the
Spyder IDE. Windows and Ubuntu; Py2 only.
WinPython: Another free distribution including scientific packages and the
Spyder IDE. Windows only, but more actively maintained and support the
latest Python 3 versions.
Pyzo: A free distribution based on Anaconda and the IEP interactive
development environment. Supports Linux, Windows and Mac.
Installing via pip - pip install numpy
Most major projects upload official packages to the Python Package index.
They can be installed on most operating systems using Python’s standard pip package
manager.Note that you need to have Python and pip already installed on your system.
You can install packages via commands such as:python -m pip install --user numpy
scipy matplotlib ipython jupyter pandas sympy nose
We recommend using a user install, using the --user flag to pip (note: do not
use sudo pip, which can cause problems). This installs packages for your local user,
and does not write to the system directories.
Experiment No:2
NumPy Basics (np.array, np.arange, np.linspace, np.zeros,
np.ones, np.random.random, np.empty)
Travis Oliphant created NumPy package in 2005 It is an extension module of
Python which is mostly written in C. It provides various functions which are capable
of performing the numeric computations with a high speed. NumPy provides various
powerful data structures, implementing multi-dimensional arrays and matrices.
NumPy stands for Numerical Python. It is a Python library used for working
with an array. . It is the library for logical computing, which contains a powerful n-
dimensional array object, gives tools to integrate C, C++ and so on. In Python, we use
the list for purpose of the array but it’s slow to process. NumPy array is a powerful
N-dimensional array object, it provides an array object much faster than traditional
Python lists.
The need of NumPy
With the revolution of data science, data analysis libraries like NumPy, SciPy,
Pandas, etc. have seen a lot of growth. With a much easier syntax than other
programming languages, python is the first choice language for the data scientist.
NumPy provides a convenient and efficient way to handle the vast amount of
data. NumPy is also very convenient with Matrix multiplication and data reshaping.
NumPy is fast which makes it reasonable to work with a large set of data.
There are the following advantages of using NumPy for data analysis.
1. NumPy performs array-oriented computing.
2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.
4. It is capable of performing Fourier Transform and reshaping the data stored in
multidimensional arrays.
5. NumPy provides the in-built functions for linear algebra and random number
generation.
Array creation routines
Types of Array:
1. One Dimensional Array
2. Multi-Dimensional Array
One Dimensional Array:
A one-dimensional array is a type of linear array.
Example:
# importing numpy module
import numpy as np
# creating list
list = [1, 2, 3, 4]
# creating numpy array
sample_array = np.array(list)
print("List in python : ", list)
print("Numpy Array in python :",sample_array)
Output:
List in python : [1, 2, 3, 4]
Numpy Array in python : [1 2 3 4]
Check data type for list and array:
print(type(list))
print(type(sample_array))
Output:
<class 'list'>
<class 'numpy.ndarray'>
Multi-Dimensional Array:
Data in multidimensional arrays are stored in tabular form.
Example:
# importing numpy module
import numpy as np
# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
# creating numpy array
sample_array = np.array([list_1, list_2, list_3])
print("Numpy multi dimensional array in python
python\n", sample_array)
Output:
Numpy multi dimensional array in python
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Note: use [ ] operators inside numpy.array() for multi
multi-dimensional
NumPy: arange() function
The arange() function is used to get evenly spaced values within a given
interval. Values are generated within the halfhalf-open
open interval [start, stop]. For integer
arguments the function is equivalent to the Python built built-in
in range function,
function but
returns an ndarray rather than a list. When using a non-integer
integer step, such as 0.1, the
results will often not be consistent
consistent.. It is better to use linspace for these cases.
Syntax:
numpy.arange([start, ]stop, [step, ]dtype=None)
Parameter:
Name Description Required/
Optional
start Start of interval. The interval includes this value. The default start Optional
value is 0.
stop End of interval. The interval does not include this value
value, except Required
in some cases where step is not an integer and floating point
round-off affects the length.
step Spacing between values. This is the distance between two Optional
adjacent values. The default step size is 1. If step is specified as
a position argument, start must also be given.
dtytpe The type of the output array. If dtype is not given, infer the data Optional
type from the other input arguments.
Return value:
arange : ndarray - Array of evenly spaced values. For floating point
arguments, the length of the result is ceil((stop - start)/step).
Example - 1:
>>> import numpy as np
>>> np.arange(5)
array([0, 1, 2, 3, 4])
>>> np.arange(5.0)
array([ 0., 1., 2., 3., 4.])
Example - 2:
>>> import numpy as np
>>> np.arange(5,9)
array([5, 6, 7, 8])
>>> np.arange(5,9,3)
array([5, 8])
NumPy: linspace() function
The linspace() function returns evenly spaced numbers over a specified interval
[start,stop].
The endpoint of the interval can optionally be excluded.
Syntax:
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
Parameter:
Name Description Required/
Optional
Start The starting value of the sequence
sequence. Required
Stop The end value of the sequence,
sequence unless endpoint is set to Required
False. In that case, the sequence consists of all but the last
of num + 1 evenly spaced samples, so that stop is
excluded. Note that the step size changes when
endpoint is False.
Num Number of samples to generate
generate. Default is 50. Must be Optional
non-negative.
Endpoint If True, stop is the last sample.
sample Otherwise, it is not Optional
included. Default is True.
True
Retstep If True, return (samples, step),
step) where step is the spacing Optional
between samples.
Dtype The type of the output array
array. If dtype is not given, infer Optional
the data type from the other input arguments.
Return value:
ndarray - There are num equally spaced samples in the closed interval [start, stop]
or the half-open interval [start, stop) (depending on whether endpoint is True or
False).
step : float, optional - Only returned if retstep is True. Size of spacing between
samples.
Example: NumPy.linspace() method
>>> import numpy as np
>>> np.linspace(3.0, 4.0, num=7)
array([ 3. , 3.16666667, 3.33333333, 3.5, 3.66666667, 3.83333333, 4. ])
>>> np.linspace(3.0,4.0, num=7, endpoint=False)
array([ 3. , 3.14285714, 3.28571429, 3.42857143, 3.57142857,3.71428571,
3.85714286])
>>> np.linspace(3.0,4.0, num=7, retstep=True)
(array([ 3. , 3.16666667, 3.33333333,3.5, 3.66666667, 3.83333333, 4. ]),
0.16666666666666666)
NumPy: zeros() function
The zeros() function is used to get a new array of given shape and type, filled with
zeros.
Syntax:
numpy.zeros(a, dtype=None, order='K')
Parameter:
Name Description Required /
Optional
shape Shape of the new array, e.g., (2, 3) or 2. Required
dtype The desired data-type for the array, e.g., numpy.int8. Optional
Default is numpy.float64.
order Whether to store multi-dimensional data in row-major (C- Optional
style) or column-major (Fortran-style) order in memory
Return value:
[ndarray] Array of zeros with the given shape, dtype, and order.
Example: numpy.zeros() function
>>> import numpy as np
>>> a = (3,2)
>>> np.zeros(a)
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
Example: numpy.zeros() where data type is int
>>> import numpy as np
>>> np.zeros(6)
array([ 0., 0., 0., 0., 0., 0.])
>>> np.zeros((6,), dtype=int)
array([0, 0, 0, 0, 0, 0])
>>> np.zeros((3, 1))
array([[ 0.],
[ 0.],
[ 0.]])
NumPy: zeros_like() function
The zeros_like() function is used to get an array of zeros with the same shape and
type as a given array.
Syntax:
numpy.zeros_like(a, dtype=None, order=’K’, subok=True)
Parameter:
Name Description Required /
Optional
A The shape and data-type of a define the same attributes Required
of the returned array.
Dtype Overrides the data type of the result. optional
Order Overrides the memory layout of the result. 'C' means C- optional
order, 'F' means F-order, 'A' means 'F' if a is Fortran
contiguous, 'C' otherwise. 'K' means match the layout of a as
closely as possible.
Subok If True, then the newly created array will use the sub-class optional
type of 'a', otherwise it will be a base-class array. Defaults to
True.
Return value:
[ndarray] Array of zeros with the same shape and type as a.
Example: numpy.zeros()
>>> import numpy as np
>>> a = np.arange(4)
>>> a = a.reshape((2, 2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.zeros_like(a)
array([[0, 0],
[0, 0]])
Example: numpy.zeros() where data type is int
>>> import numpy as np
>>> b = np.arange(5, dtype=int)
>>> b
array([ 0., 1., 2., 3., 4.])
>>> np.zeros_like(b)
array([ 0., 0., 0., 0., 0.])
NumPy: ones() function
The ones() function is used to get a new array of given shape and type, filled with
ones.
Syntax:
numpy.ones(shape, dtype=None, order='C')
Parameter:
Name Description Required
/
Optional
shape Shape of the new array, e.g., (2, 3) or 2. Required
dtype The desired data-type for the array, e.g., numpy.int8. Default is optional
numpy.float64.
order Whether to store multi-dimensional data in row-major (C-style) or optional
column-major (Fortran-style) order in memory
Return value:
[ndarray] Array of ones with the given shape, dtype, and order.
Example-1: numpy.ones()
>>> import numpy as np
>>> np.ones(7)
array([ 1., 1., 1., 1., 1., 1., 1.])
>>> np.ones((2, 1))
array([[ 1.],
[ 1.]])
>>> x = (2, 3)
>>> np.ones(x)
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
Example-2: numpy.ones() where data type is int
>>> import numpy as np
>>> np.ones((2,2)) #default datatype float
array([[ 1., 1.],
[ 1., 1.]])
>>> np.ones((2,2), dtype=int)
array([[1, 1],
[1, 1]])
>>>
NumPy: ones_like() function
The ones_like() function is used to get an array of ones with the same shape and
type as a given array.
Syntax:
numpy.ones_like(a, dtype=None, order='K', subok=True)
Name Description Required
/
Optional
a The shape and data-type of a define these same attributes of the Required
returned array
dtype Overrides the data type of the result. New in version 1.6.0. optional
order Overrides the memory layout of the result. 'C' means C-order, 'F' optional
means F-order, 'A' means 'F' if a is Fortran contiguous, 'C' otherwise.
'K' means match the layout of a as closely as possible.
subok If True, then the newly created array will use the sub-class type of ‘a’, optional
otherwise it will be a base-class array. Defaults to True.
Return value:
[ndarray] Array of ones with the same shape and type as a.
Example: numpy.ones_like() function
>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2,3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.ones_like(x)
array([[1, 1, 1],
[1, 1, 1]])
Copy
Pictorial Presentation:
Example: numpy.ones_like where data type is int
>>> import numpy as np
>>> a = np.arange(5, dtype=int)
>>> a
array([0, 1, 2, 3, 4])
>>> np.ones_like(a)
array([1, 1, 1, 1, 1])
numpy.random() in Python
The random is a module present in the NumPy library. This module contains the
functions which are used for generating random numbers. This module contains
some simple random data generation methods, some permutation and distribution
functions, and random generator functions.
All the functions in a random module are as follows:
Simple random data
There are the following functions of simple random data:
1) p.random.rand(d0, d1, ..., dn)
This function of random module is used to generate random numbers or values in a
given shape.
Example:
import numpy as np
a=np.random.rand(5,2)
a
Output:
array([[0.74710182, 0.13306399],
[0.01463718, 0.47618842],
[0.98980426, 0.48390004],
[0.58661785, 0.62895758],
[0.38432729, 0.90384119]])
2) np.random.randint(low[, high, size, dtype])
This function of random module is used to generate random integers from
inclusive(low) to exclusive(high).
Example:
import numpy as np
a=np.random.randint(3, size=10)
a
Output:
array([1, 1, 1, 2, 0, 0, 0, 0, 0, 0])
3) np.random.ranf([size])
This function of random module is used to generate random floats number in the
half-open interval [0.0, 1.0).
Example:
import numpy as np
a=np.random.ranf()
a
b=type(np.random.ranf())
b
c=np.random.ranf((5,))
c
Output:
0.2907792098474542
<type 'float'>
array([0.34084881, 0.07268237, 0.38161256, 0.46494681, 0.88071377])
NumPy: empty() function
The empty() function is used to create a new array of given shape and type,
without initializing entries(filled
(filled with some random values).
Syntax:
numpy.empty(shape, dtype=float, order='C')
Parameter:
Name Description Required /
Optional
shape Shape of the empty array, e.g., (2, 3) or 2. Required
dtype Desired output data
data-type for the array, e.g, numpy.int8. optional
Default is numpy.float64.
order Whether to store multi
multi-dimensional data in row-major (C- optional
style) or column-major
major (Fortran
(Fortran-style) order in memory.
Example: numpy.empty() function
>>> import numpy as np
>>> np.empty(2)
array([ 6.95033087e-310, 1.69970835e
1.69970835e-316])
>>> np.empty([2, 3])
array([[ 6.95033087e-310, 1.68240973e
1.68240973e-316, 6.95032825e-310],
[ 6.95032825e-310, 6.95032825e
6.95032825e-310, 6.95032825e-310]])
Example: numpy.empty() where data
data-type for the array is int
>>>import numpy as np
>>> np.empty([2, 2], dtype=int
int)
array([[140144669465496, 16250304],
[140144685653488, 140144685468840]])
>>> np.empty([2, 2], dtype=float)
array([[2.37015306e-316, 7.37071328e-315],
[9.06655519e-317, 2.00753892e-317]])