0% found this document useful (0 votes)
11 views

Numpy

Uploaded by

sreelakshmimr009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Numpy

Uploaded by

sreelakshmimr009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 54

NumPy

NumPy, which stands for Numerical Python, is a library consisting


of multidimensional array objects and a collection of routines for
processing those arrays. Using NumPy, mathematical and logical
operations on arrays can be performed. Travis Oliphant created
NumPy package in 2005 by injecting the features of the ancestor
module Numeric into another module Numarray.
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. These data structures
are used for the optimal computations regarding arrays and matrices.
The need of NumPy
With the revolution of data science, data analysis libraries
like NumPy, SiPcy, 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.

NumPy performs array-oriented computing.


It efficiently implements the multidimensional arrays.
It performs scientific computations.
It is capable of performing Fourier Transform and reshaping the data
stored in multidimensional arrays.
NumPy provides the in-built functions for linear algebra and random
number generation.

----------------------------------
NumPy - Ndarray Object
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.

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.

numpy.array(object, dtype = None, copy = True, order = None,


subok = False, ndmin = 0)
1
object

Any object exposing the array interface method returns an array, or any (nested)
sequence.
2
dtype

Desired data type of array, optional


3
copy

Optional. By default (true), the object is copied


4
order

C (row major) or F (column major) or A (any) (default)


5
subok

By default, returned array forced to be a base class array.


If true, sub-classes
passed through

6
ndmin

Specifies minimum dimensions of resultant array


--------------------
import numpy as np
a = np.array([1,2,3])
print(a)

output:
[1, 2, 3]
----------------------
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a)

output:
[[1 2]
[3 4]]
----------------------------
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print(a)

output:
[[1 2 3 4 5]]
----------------------
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print(a)

output:
[1.+0.j 2.+0.j 3.+0.j]
--------------------------------
NumPy - Data Types
NumPy supports a much greater variety of numerical types than Python
does. The following table shows different scalar data types defined
in NumPy.

1
bool_

Boolean (True or False) stored as a byte

2
int_

Default integer type (same as C long; normally either int64 or int32)

3
intc

Identical to C int (normally int32 or int64)

4
intp

Integer used for indexing (same as C ssize_t; normally either int32 or int64)
5
int8

Byte (-128 to 127)

6
int16

Integer (-32768 to 32767)

7
int32

Integer (-2147483648 to 2147483647)


8
int64

Integer (-9223372036854775808 to 9223372036854775807)

9
uint8

Unsigned integer (0 to 255)

10
uint16

Unsigned integer (0 to 65535)

11
uint32

Unsigned integer (0 to 4294967295)


12
uint64

Unsigned integer (0 to 18446744073709551615)


13
float_

Shorthand for float64

14
float16

Half precision float: sign bit, 5 bits exponent, 10 bits mantissa


15
float32

Single precision float: sign bit, 8 bits exponent, 23 bits mantissa

16
float64

Double precision float: sign bit, 11 bits exponent, 52 bits mantissa

17
complex_

Shorthand for complex128


18
complex64

Complex number, represented by two 32-bit floats (real and imaginary components)

19
complex128

Complex number, represented by two 64-bit floats (real and imaginary components)
----------------------------
# using array-scalar type
import numpy as np
dt = np.dtype(np.int32)
print(dt)

output:
int32
-----------------
#int8, int16, int32, int64 can be replaced by equivalent string
'i1', 'i2','i4', etc.
import numpy as np

dt = np.dtype('i4')
print(dt)

output:
int32

-------------------
Use of structured data type. Here, the field name and the corresponding
scalar data type is to be declared.

# first create structured data type


import numpy as np
dt = np.dtype([('age',np.int8)])
print(dt)

output:
[('age', 'i1')]
-------------------------------
# now apply it to ndarray object
import numpy as np

dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print(a)

output:
[(10,) (20,) (30,)]
--------------------------------
# field 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'])

output:
[10 20 30]
---------------------
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)

output:
[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]

----------------------------------
import numpy as np

student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])


a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print(a)

output:
[(b'abc', 21, 50.) (b'xyz', 18, 75.)]
-----------------------------
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)


------------------------
NumPy - Array Attributes
ndarray.shape
This array attribute returns a tuple consisting of array dimensions.
It can also be used to resize the array.
-----------------------------------
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
print(a.shape)

output:
[[1 2 3]
[4 5 6]]

(2, 3)
--------------------
# this resizes the ndarray
import numpy as np

a = np.array([[1,2,3],[4,5,6]])
print(a)
a.shape = (3,2)
print(a)

output:

[[1 2 3]
[4 5 6]]

[[1 2]
[3 4]
[5 6]]
---------------------

NumPy also provides a reshape function to resize an array.


------------------------
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
b = a.reshape(3,2)
print(b)

output:
[[1 2 3]
[4 5 6]]

[[1 2]
[3 4]
[5 6]]
--------------------------------
ndarray.ndim
This array attribute returns the number of array dimensions.
# an array of evenly spaced numbers

import numpy as np
a = np.arange(24)
print(a)

output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
--------------------------------
# this is one dimensional array

import numpy as np
a = np.arange(24)
print(a)
print(a.ndim)

output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
1
------------------------------
numpy.itemsize
This array attribute returns the length of each element of array in bytes.
-------------------
# dtype of array is int8
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print(x)
print(x.itemsize)

output:
[1 2 3 4 5]
1
---------------------
# 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)
print(x.itemsize)

output:
[1. 2. 3. 4. 5.]
4
----------------------------
NumPy - Array Creation Routines
numpy.empty
It creates an uninitialized array of specified shape and dtype. It uses the
following constructor −

numpy.empty(shape, dtype = float, order = 'C')

1
Shape

Shape of an empty array in int or tuple of int


2
Dtype

Desired output data type. Optional

3
Order

'C' for C-style row-major array F' for FORTRAN style column-major array
--------------------------
import numpy as np
x = np.empty([3,2], dtype = int)
print(x)

output:
[[6357058 6946921]
[6029429 7340097]
[4456560 7602273]]
-----------------------------------
numpy.zeros
Returns a new array of specified size, filled with zeros.

numpy.zeros(shape, dtype = float, order = 'C')

1
Shape

Shape of an empty array in int or sequence of int

2
Dtype

Desired output data type. Optional

3
Order

'C' for C-style row-major array, 'F' for FORTRAN style column-major array
------------------------------------------
# array of five zeros. Default dtype is float
import numpy as np
x = np.zeros(5)
print(x)

output:
[0. 0. 0. 0. 0.]
----------------------------
import numpy as np
x = np.zeros((5,), dtype = np.int8)
print(x)

output:
[0 0 0 0 0]
--------------------------------
# custom type
import numpy as np
x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print(x)
output:
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]
--------------------------
numpy.ones
Returns a new array of specified size and type, filled with ones.

numpy.ones(shape, dtype = None, order = 'C')


1
Shape

Shape of an empty array in int or tuple of int

2
Dtype

Desired output data type. Optional

3
Order

'C' for C-style row-major array, 'F' for FORTRAN style column-major array
---------------------------------
# array of five ones. Default dtype is float
import numpy as np
x = np.ones(5)
print(x)

output:
[1. 1. 1. 1. 1.]
---------------------------------------
import numpy as np
x = np.ones([2,2], dtype = int)
print(x)

output:
[[1 1]
[1 1]]
-----------------
numpy.fromiter
This function builds an ndarray object from any iterable object. A new
one-dimensional array is returned by this function.
numpy.fromiter(iterable, dtype, count = -1)
1
iterable

Any iterable object

2
dtype

Data type of resultant array

3
count

The number of items to be read from iterator. Default is -1 which means all data to
be read
---------------------
# obtain iterator object from list
import numpy as np
list = range(5)
it = iter(list)

# use iterator to create ndarray


x = np.fromiter(it, dtype = float)
print(x)

output:
[0. 1. 2. 3. 4.]
--------------------------------------
NumPy - 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 −

numpy.arange(start, stop, step, dtype)


1
start

The start of an interval. If omitted, defaults to 0

2
stop

The end of an interval (not including this number)

3
step

Spacing between values, default is 1

4
dtype

Data type of resulting ndarray. If not given, data type of input is used

-------------------------------
import numpy as np
x = np.arange(5)
print(x)

output:
[0 1 2 3 4]
----------------------------
import numpy as np
# dtype set
x = np.arange(5, dtype = float)
print(x)
output:
[0. 1. 2. 3. 4.]
---------------------
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print(x)

output:
[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.
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
1
start

The starting value of the sequence

2
stop

The end value of the sequence, included in the sequence if endpoint set to true

3
num

The number of evenly spaced samples to be generated. Default is 50

4
endpoint

True by default, hence the stop value is included in the sequence.


If false, it is not included

5
retstep

If true, returns samples and step between the consecutive numbers

6
dtype

Data type of output ndarray


-------------------------------
import numpy as np
x = np.linspace(10,20,5)
print(x)
output:
[10. 12.5 15. 17.5 20. ]
-----------------------------
# endpoint set to false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print(x)

output:
[10. 12. 14. 16. 18.]
---------------------
# find retstep value
import numpy as np
x = np.linspace(1,2,5, retstep = True)
print(x)

output:
(array([1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
-------------------------------------------
NumPy - Indexing & Slicing
Contents of ndarray object can be accessed and modified by indexing
or slicing, just like Python's in-built container objects.

Basic slicing is an extension of Python's basic concept of slicing


to n dimensions. A Python slice object is constructed by giving start,
stop, and step parameters to the built-in slice function. This slice
object is passed to the array to extract a part of array.
------------------------
import numpy as np
a = np.arange(10)
print(a)
s = slice(2,7,2)
print(a[s])

output:
[0 1 2 3 4 5 6 7 8 9]
[2 4 6]
-----------------
Slicing parameters separated by a colon : (start:stop:step) directly
to the ndarray object.

import numpy as np
a = np.arange(10)
print(a)
b = a[2:7:2]
print(b)

output:
[0 1 2 3 4 5 6 7 8 9]
[2 4 6]
----------------------
# slice single item
import numpy as np

a = np.arange(10)
print(a)
b = a[5]
print(b)

output:
[0 1 2 3 4 5 6 7 8 9]
5
-----------------------------
# slice items between indexes
import numpy as np
a = np.arange(10)
print(a)
print(a[2:5])

output:
[0 1 2 3 4 5 6 7 8 9]
[2 3 4]
--------------------------
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print(a)
# slice items starting from index
print('Now we will slice the array from the index a[1:]')
print(a[1:])

output:
[[1 2 3]
[3 4 5]
[4 5 6]]
Now we will slice the array from the index a[1:]
[[3 4 5]
[4 5 6]]
----------------------------------
Slicing can also include ellipsis (…) to make a selection tuple of
the same length as the dimension of an array. If ellipsis is used
at the row position, it will return an ndarray comprising of items in rows.
# array to begin with
----------------------------
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print('Our array is:')
print(a)
# this returns array of items in the second column
print('The items in the second column are:')
print(a[..., 1])
print('\n')

# Now we will slice all items from the second row


print('The items in the second row are:')
print(a[1, ...])
print('\n')

# Now we will slice all items from column 1 onwards


print('The items column 1 onwards are:')
print (a[...,1:])

output:

Our array is:


[[1 2 3]
[3 4 5]
[4 5 6]]

The items in the second column are:


[2 4 5]

The items in the second row are:


[3 4 5]

The items column 1 onwards are:


[[2 3]
[4 5]
[5 6]]
-----------------------
NumPy - Advanced Indexing
There are two types of advanced indexing − Integer and Boolean.

Integer Indexing
This mechanism helps in selecting any arbitrary item in an array
based on its Ndimensional index. Each integer array represents the
number of indexes into that dimension. When the index consists of
as many integer arrays as the dimensions of the target ndarray,
it becomes straightforward.
------------------
import numpy as np
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x)
y = x[[0,1,2], [0,1,0]]
print(y)

output:
[[1 2]
[3 4]
[5 6]]

[1 4 5]

The selection includes elements at (0,0), (1,1) and (2,0) from the
first array.
-----------------------------------
import numpy as np
x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
print('Our array is:')
print(x)
print('\n')

rows = np.array([[0, 0], [3, 3]])


cols = np.array([[0, 2], [0, 2]])
y = x[rows, cols]

print('The corner elements of this array are:')


print(y)

output:
Our array is:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]

The corner elements of this array are:


[[ 0 2]
[ 9 11]]
--------------------------
Boolean Array Indexing
This type of advanced indexing is used when the resultant object
is meant to be the result of Boolean operations, such as comparison
operators.

Items greater than 5 are returned as a result of Boolean indexing.


------------------
import numpy as np
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
print('Our array is:')
print(x)
print('\n')
# Now we will print the items greater than 5
print('The items greater than 5 are:')
print(x[x > 5])

output:
Our array is:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]

The items greater than 5 are:


[ 6 7 8 9 10 11]
---------------------------------
NumPy - Broadcasting
The term broadcasting refers to the ability of NumPy to treat arrays of
different shapes during arithmetic operations.
Arithmetic operations on arrays are usually done on corresponding elements.
If two arrays are of exactly the same shape, then these operations are
smoothly performed.
---------------
import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c = a * b
print(c)

output:
[ 10 40 90 160]

If the dimensions of two arrays are dissimilar, element-to-element


operations are not possible. However, operations on arrays of non-similar
shapes is still possible in NumPy, because of the broadcasting capability.
The smaller array is broadcast to the size of the larger array so that
they have compatible shapes.

Size in each dimension of the output shape is maximum of the input sizes
in that dimension. An input can be used in calculation, if its size in a
particular dimension matches the output size or its value is exactly 1.

If an input has a dimension size of 1, the first data entry in that


dimension is used for all calculations along that dimension.
---------------------
import numpy as np
a = np.array([[0.0, 0.0, 0.0], [10.0, 10.0, 10.0], [20.0, 20.0, 20.0], [30.0, 30.0,
30.0]])
b = np.array([1.0, 2.0, 3.0])
print('First array:')
print(a)

print('Second array:')
print(b)

print('First Array + Second Array')


print(a + b)

output:
First array:
[[ 0. 0. 0.]
[10. 10. 10.]
[20. 20. 20.]
[30. 30. 30.]]
Second array:
[1. 2. 3.]
First Array + Second Array
[[ 1. 2. 3.]
[11. 12. 13.]
[21. 22. 23.]
[31. 32. 33.]]
--------------------------------
NumPy - Iterating Over Array
NumPy package contains an iterator object numpy.nditer. It is an efficient
multidimensional iterator object using which it is possible to iterate
over an array. Each element of an array is visited using Python’s standard
Iterator interface.
---------------
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print('Original array is:')


print(a)

print('Modified array is:')


for x in np.nditer(a):
print(x, end=' ')

output:
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Modified array is:
0 5 10 15 20 25 30 35 40 45 50 55

---------------------------------------
Iterating over the transpose of the above array.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print('Original array is:')


print(a)

print('Transpose of the original array is:')


b = a.T
print(b)

print('Modified array is:')


for x in np.nditer(b):
print(x, end=' ')

output:
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Transpose of the original array is:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
Modified array is:
0 5 10 15 20 25 30 35 40 45 50 55
------------------------------------------
Iteration Order
If the same elements are stored using F-style order, the iterator chooses the more
efficient way of iterating
over an array.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print('Original array is:')


print(a)

print('Transpose of the original array is:')


b = a.T
print(b)

print('Sorted in C-style order:')


c = b.copy(order = 'C')
print(c)
for x in np.nditer(c):
print(x, end=' ')

print('Sorted in F-style order:')


c = b.copy(order = 'F')
print(c)
for x in np.nditer(c):
print(x, end=' ')

output:
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Transpose of the original array is:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
Sorted in C-style order:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
0 20 40 5 25 45 10 30 50 15 35 55 Sorted in F-style order:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
0 5 10 15 20 25 30 35 40 45 50 55

-------------------------------
NumPy - Array Manipulation
Several routines are available in NumPy package for manipulation of elements in
ndarray object.
--------------
Changing Shape:
numpy.reshape
This function gives a new shape to an array without changing the data. It accepts
the following parameters −
numpy.reshape(arr, newshape, order')

import numpy as np
a = np.arange(8)
print('The original array:')
print(a)
b = a.reshape(4,2)
print('The modified array:')
print(b)

output:
The original array:
[0 1 2 3 4 5 6 7]
The modified array:
[[0 1]
[2 3]
[4 5]
[6 7]]
--------------
numpy.ndarray.flat
This function returns a 1-D iterator over the array. It behaves similar to Python's
built-in iterator.
import numpy as np
a = np.arange(8).reshape(2,4)
print('The original array:')
print(a)

print('After applying the flat function:')


# returns element corresponding to index in flattened array
print(a.flat[5])

output:
The original array:
[[0 1 2 3]
[4 5 6 7]]
After applying the flat function:
5

-----------------
numpy.ndarray.flatten
This function returns a copy of an array collapsed into one dimension. The function
takes the following parameters.

ndarray.flatten(order)

import numpy as np
a = np.arange(8).reshape(2,4)

print('The original array is:')


print(a)
# default is column-major

print('The flattened array is:')


print(a.flatten())

print('The flattened array in F-style ordering:')


print(a.flatten(order='F'))

output:
The original array is:
[[0 1 2 3]
[4 5 6 7]]
The flattened array is:
[0 1 2 3 4 5 6 7]
The flattened array in F-style ordering:
[0 4 1 5 2 6 3 7]
--------------------
Transpose Operations
numpy.transpose
This function permutes the dimension of the given array. It returns a view
wherever possible. The function takes the following parameters.
-----------------------------
numpy.transpose(arr)
import numpy as np
a = np.arange(12).reshape(3,4)

print('The original array is:')


print(a)

print('The transposed array is:')


print(np.transpose(a))

Output:
The original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
The transposed array is:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
----------------------------
numpy.ndarray.T
This function belongs to ndarray class. It behaves similar to numpy.transpose.
import numpy as np
a = np.arange(12).reshape(3,4)

print('The original array is:')


print(a)

print('Array after applying the function:')


print(a.T)

output:
The original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Array after applying the function:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]

---------------------
Joining Arrays
numpy.concatenate
Concatenation refers to joining. This function is used to join two or more arrays
of the same shape along a
specified axis. The function takes the following parameters.

numpy.concatenate((a1, a2, ...), axis)


--------------------------
import numpy as np
a = np.array([[1,2],[3,4]])

print('First array:')
print(a)

b = np.array([[5,6],[7,8]])

print('Second array:')
print(b)

# both the arrays are of same dimensions

print('Joining the two arrays along axis 0:')


print(np.concatenate((a, b)))

print('Joining the two arrays along axis 1:')


print(np.concatenate((a, b), axis=1))

output:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Joining the two arrays along axis 0:
[[1 2]
[3 4]
[5 6]
[7 8]]
Joining the two arrays along axis 1:
[[1 2 5 6]
[3 4 7 8]]
-----------------------------
numpy.stack
This function joins the sequence of arrays along a new axis.
numpy.stack(arrays, axis)
------------------
import numpy as np
a = np.array([[1,2],[3,4]])

print('First Array:')
print(a)

b = np.array([[5,6],[7,8]])

print('Second Array:')
print(b)

print('Stack the two arrays along axis 0:')


print(np.stack((a, b), 0))

print('Stack the two arrays along axis 1:')


print(np.stack((a, b), 1))

output:
First Array:
[[1 2]
[3 4]]
Second Array:
[[5 6]
[7 8]]
Stack the two arrays along axis 0:
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]
Stack the two arrays along axis 1:
[[[1 2]
[5 6]]

[[3 4]
[7 8]]]

------------------------------------
numpy.hstack
Variants of numpy.stack function to stack so as to make a single array
horizontally.

import numpy as np
a = np.array([[1,2],[3,4]])

print('First array:')
print(a)

b = np.array([[5,6],[7,8]])

print('Second array:')
print(b)

print('Horizontal stacking:')
c = np.hstack((a,b))
print(c)

output:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Horizontal stacking:
[[1 2 5 6]
[3 4 7 8]]

---------------------
numpy.vstack
Variants of numpy.stack function to stack so as to make a single array
vertically.

import numpy as np
a = np.array([[1,2],[3,4]])

print('First array:')
print(a)

b = np.array([[5,6],[7,8]])

print('Second array:')
print(b)

print('Vertical stacking:')
c = np.vstack((a,b))
print(c)

output:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
Vertical stacking:
[[1 2]
[3 4]
[5 6]
[7 8]]
-------------------------
NumPy - Array Manipulation
Splitting Arrays

This function divides the array into subarrays along a specified axis.
The function takes three parameters.

numpy.split(ary, indices_or_sections, axis)


1
ary

Input array to be split

2
indices_or_sections

Can be an integer, indicating the number of equal sized subarrays to be created


from the input array. If this parameter is a 1-D array, the entries indicate the
points at which a new subarray is to be created.

3
axis
Default is 0
---------------------------
import numpy as np
a = np.arange(9)
print('First array:')
print(a)
print('Split the array in 3 equal-sized subarrays:')
b = np.split(a,3)
print(b)

print('Split the array at positions indicated in 1-D array:')


b = np.split(a,[4,7])
print(b)

output:
First array:
[0 1 2 3 4 5 6 7 8]
Split the array in 3 equal-sized subarrays:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
Split the array at positions indicated in 1-D array:
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]

----------------------
numpy.hsplit
The numpy.hsplit is a special case of split() function where axis is 1
indicating a horizontal
split regardless of the dimension of the input array.
import numpy as np
a = np.arange(16).reshape(4,4)

print('First array:')
print(a)

print('Horizontal splitting:')
b = np.hsplit(a,2)
print(b)

output:
First array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
Horizontal splitting:
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]

--------------
numpy.vsplit
numpy.vsplit is a special case of split() function where axis is 1
indicating a vertical split regardless of the dimension of the
input array. The following example makes this clear.
import numpy as np
a = np.arange(16).reshape(4,4)

print('First array:')
print(a)

print('Vertical splitting:')
b = np.vsplit(a,2)
print(b)

Output:
First array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
Vertical splitting:
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
-----------------------
Adding / Removing Elements
numpy.resize
This function returns a new array with the specified size. If the new
size is greater than the original, the repeated copies of entries in
the original are contained. The function takes the following parameters.

numpy.resize(arr, shape)
1
arr

Input array to be resized

2
shape

New shape of the resulting array

import numpy as np
a = np.array([[1,2,3],[4,5,6]])

print('First array:')
print(a)

print('The shape of first array:')


print(a.shape)

b = np.resize(a, (3,2))

print('Second array:')
print(b)

print('The shape of second array:')


print(b.shape)

# Observe that first row of a is repeated in b since size is bigger

print('Resize the second array:')


b = np.resize(a,(3,3))
print(b)

output:
First array:
[[1 2 3]
[4 5 6]]
The shape of first array:
(2, 3)
Second array:
[[1 2]
[3 4]
[5 6]]
The shape of second array:
(3, 2)
Resize the second array:
[[1 2 3]
[4 5 6]
[1 2 3]]

----------------
numpy.append
This function adds values at the end of an input array. The append
operation is not inplace, a new array is allocated. Also the dimensions
of the input arrays must match otherwise ValueError will be generated.

The function takes the following parameters.

numpy.append(arr, values, axis)


1
arr

Input array

2
values

To be appended to arr. It must be of the same shape as of arr


(excluding axis of appending)

3
axis

The axis along which append operation is to be done. If not given,


both parameters are flattened
------------------------------------
import numpy as np
a = np.array([[1,2,3],[4,5,6]])

print('First array:')
print(a)

b = np.array([7, 8, 9])
print('Second array:')
print(b)
print('Append elements to array:')
print(np.append(a, b))

print('Append elements along axis 0:')


print(np.append(a, [[7, 8, 9]], axis=0))
print('Append elements along axis 1:')
print(np.append(a, [[5, 5, 5], [7, 8, 9]], axis=1))

output:
First array:
[[1 2 3]
[4 5 6]]
Second array:
[7 8 9]
Append elements to array:
[1 2 3 4 5 6 7 8 9]
Append elements along axis 0:
[[1 2 3]
[4 5 6]
[7 8 9]]
Append elements along axis 1:
[[1 2 3 5 5 5]
[4 5 6 7 8 9]]
------------------
numpy.insert
This function inserts values in the input array along the given axis
and before the given index. If the type of values is converted to be
inserted, it is different from the input array. Insertion is not done
in place and the function returns a new array. Also, if the axis is not
mentioned, the input array is flattened.

The insert() function takes the following parameters −

numpy.insert(arr, pos, values, axis)


1
arr

Input array

2
pos

The index before which insertion is to be made

3
values

The array of values to be inserted

4
axis

The axis along which to insert. If not given, the input array is flattened
-----------------------------------
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])

print('First array:')
print(a)

print('Axis parameter not passed. The input array is flattened before insertion.')
print(np.insert(a, 3, [11, 12]))
print('Axis parameter passed. The values array is broadcast to match input array.')

print('Broadcast along axis 0:')


print(np.insert(a, 1, [11], axis=0))

print('Broadcast along axis 1:')


print(np.insert(a, 1, 11, axis=1))

output:
First array:
[[1 2]
[3 4]
[5 6]]
Axis parameter not passed. The input array is flattened before insertion.
[ 1 2 3 11 12 4 5 6]
Axis parameter passed. The values array is broadcast to match input array.
Broadcast along axis 0:
[[ 1 2]
[11 11]
[ 3 4]
[ 5 6]]
Broadcast along axis 1:
[[ 1 11 2]
[ 3 11 4]
[ 5 11 6]]
---------------------------------
numpy.delete
This function returns a new array with the specified subarray deleted from
the input array. As in case of insert() function, if the axis parameter
is not used, the input array is flattened.
The function takes the following parameters −

Numpy.delete(arr, obj, axis)


1
arr

Input array

2
obj

Can be a slice, an integer or array of integers, indicating the subarray


to be deleted from the input array

3
axis

The axis along which to delete the given subarray. If not given, arr is flattened
-----------------------------------
import numpy as np
a = np.arange(12).reshape(3,4)

print('First array:')
print(a)

print('Array flattened before delete operation as axis not used:')


print(np.delete(a, 5))

print('Column 2 deleted:')
print(np.delete(a, 1, axis=1))

Output:
First array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Array flattened before delete operation as axis not used:
[ 0 1 2 3 4 6 7 8 9 10 11]
Column 2 deleted:
[[ 0 2 3]
[ 4 6 7]
[ 8 10 11]]

---------------
numpy.unique
This function returns an array of unique elements in the input array.
The function can be able to return a tuple of array of unique vales and
an array of associated indices. Nature of the indices depend upon the
type of return parameter in the function call.

numpy.unique(arr, return_index, return_inverse, return_counts)


1
arr

The input array. Will be flattened if not 1-D array

2
return_index

If True, returns the indices of elements in the input array

3
return_inverse

If True, returns the indices of unique array, which can be used to reconstruct the
input array

4
return_counts

If True, returns the number of times the element in unique array appears in the
original array
--------------------------------
import numpy as np
a = np.array([5,2,6,2,7,5,6,8,2,9])

print('First array:')
print(a)
print('\n')

print('Unique values of first array:')


u = np.unique(a)
print(u)
print('\n')

print('Unique array and Indices array:')


u,indices = np.unique(a, return_index = True)
print(indices)
print('\n')

print('We can see each number corresponds to index in original array:')


print(a)
print('\n')

print('Indices of unique array:')


u,indices = np.unique(a,return_inverse = True)
print(u)
print('\n')

print('Indices are:')
print(indices)
print('\n')

print('Reconstruct the original array using indices:')


print(u[indices])
print('\n')

print('Return the count of repetitions of unique elements:')


u,indices = np.unique(a,return_counts = True)
print(u)
print(indices)

output:
First array:
[5 2 6 2 7 5 6 8 2 9]

Unique values of first array:


[2 5 6 7 8 9]

Unique array and Indices array:


[1 0 2 4 7 9]

We can see each number corresponds to index in original array:


[5 2 6 2 7 5 6 8 2 9]

Indices of unique array:


[2 5 6 7 8 9]

Indices are:
[1 0 2 0 3 1 2 4 0 5]

Reconstruct the original array using indices:


[5 2 6 2 7 5 6 8 2 9]

Return the count of repetitions of unique elements:


[2 5 6 7 8 9]
[3 2 2 1 1 1]

-----------------
NumPy - String Functions
standard string functions in Python's built-in library.
numpy.char.add()
This function performs elementwise string concatenation.
----------------------
import numpy as np

print('Concatenate two strings:')


print(np.char.add(['hello'], [' xyz']))
print('\n')

print('Concatenation example:')
print(np.char.add(['hello', 'hi'], [' abc', ' xyz']))

output:
Concatenate two strings:
['hello xyz']

Concatenation example:
['hello abc' 'hi xyz']

------------------------------
numpy.char.multiply()
This function performs multiple concatenation.
import numpy as np

print(np.char.multiply('Hello ', 3))

output:
Hello Hello Hello
---------------------------
numpy.char.center()
This function returns an array of the required width so that the input string is
centered and padded on the
left and right with fillchar.
-------------------------
import numpy as np
# np.char.center(arr, width,fillchar)
print(np.char.center('hello', 20, fillchar='*'))

output:
*******hello********
-----------------------------
numpy.char.capitalize()
This function returns the copy of the string with the first letter
capitalized.
----------------------------
import numpy as np
print(np.char.capitalize('hello world'))
output:
Hello world
-------------------------------
numpy.char.title()
This function returns a title cased version of the input string with the
first letter of each word capitalized.
--------------------------
import numpy as np
print(np.char.title('hello how are you?'))

output:
Hello How Are You?
-----------------------------
numpy.char.lower()
This function returns an array with elements converted to lowercase. It calls
str.lower for each element.
-----------------------
import numpy as np
print(np.char.lower(['HELLO', 'WORLD']))
print(np.char.lower('HELLO'))

output:
['hello' 'world']
hello

-----------------------
numpy.char.upper()
This function calls str.upper function on each element in an array to return the
uppercase array elements.
-------------------------------------
import numpy as np
print(np.char.upper('hello'))
print(np.char.upper(['hello', 'world']))

output:
HELLO
['HELLO' 'WORLD']

------------------------------------------
numpy.char.split()
This function returns a list of words in the input string. By default, a whitespace
is used as a separator.
Otherwise the specified separator character is used to spilt the string.
------------------------------
import numpy as np
print(np.char.split('hello how are you?'))
print(np.char.split('India, is my ,country', sep=','))

output:
['hello', 'how', 'are', 'you?']
['India', ' is my ', 'country']

----------------------------------------
numpy.char.strip()
This function returns a copy of array with elements stripped of the
specified characters leading and/or trailing in it.
---------------------------
import numpy as np
print(np.char.strip('ashok arora', 'a'))
print(np.char.strip(['arora', 'admin', 'java'], 'a'))

output:
shok aror
['ror' 'dmin' 'jav']

----------------

numpy.char.join()
This method returns a string in which the individual characters are joined by
separator character specified.
------------------------------
import numpy as np
print(np.char.join(':', 'dmy'))
print(np.char.join([':', '-'], ['dmy', 'ymd']))

output:
d:m:y
['d:m:y' 'y-m-d']

-----------------------
numpy.char.replace()
This function returns a new copy of the input string in which all
occurrences of the sequence of characters is
replaced by another given sequence
--------------------------------
import numpy as np
print(np.char.replace('He is a good boy', 'is', 'was'))

output:
He was a good boy

-----------------------------------------------------
NumPy - Mathematical Functions:

Quite understandably, NumPy contains a large number of various mathematical


operations. NumPy provides standard trigonometric functions, functions for
arithmetic operations, handling complex numbers, etc.
Trigonometric Functions
NumPy has standard trigonometric functions which return trigonometric
ratios for a given angle in radians.
-------------------
import numpy as np
a = np.array([0,30,45,60,90])
print('Sine of different angles:')
# Convert to radians by multiplying with pi/180
print(np.sin(a * np.pi / 180))
print('\n')

print('Cosine values for angles in array:')


print(np.cos(a * np.pi / 180))
print('\n')

print('Tangent values for given angles:')


print(np.tan(a * np.pi / 180))

output:
Sine of different angles:
[0. 0.5 0.70710678 0.8660254 1. ]

Cosine values for angles in array:


[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]

Tangent values for given angles:


[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
------------------------------------------
arcsin, arcos, and arctan functions return the trigonometric
inverse of sin, cos, and tan of the given angle. The result
of these functions can be verified by numpy.degrees()
function by converting radians to degrees.
----------------------------
import numpy as np
a = np.array([0,30,45,60,90])
print('Array containing sine values:')
sin = np.sin(a*np.pi/180)
print(sin)
print('\n')

print('Compute sine inverse of angles. Returned values are in radians.')


inv = np.arcsin(sin)
print(inv)
print('\n')

print('Check result by converting to degrees:')


print(np.degrees(inv))
print('\n')

print('arccos and arctan functions behave similarly:')


cos = np.cos(a*np.pi/180)
print(cos)
print('\n')

print('Inverse of cos:')
inv = np.arccos(cos)
print(inv)
print('\n')

print('In degrees:')
print(np.degrees(inv))
print('\n')

print('Tan function:')
tan = np.tan(a*np.pi/180)
print(tan)
print('\n')

print('Inverse of tan:')
inv = np.arctan(tan)
print(inv)
print('\n')

print('In degrees:')
print(np.degrees(inv))

output:
Array containing sine values:
[0. 0.5 0.70710678 0.8660254 1. ]

Compute sine inverse of angles. Returned values are in radians.


[0. 0.52359878 0.78539816 1.04719755 1.57079633]

Check result by converting to degrees:


[ 0. 30. 45. 60. 90.]
arccos and arctan functions behave similarly:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]

Inverse of cos:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]

In degrees:
[ 0. 30. 45. 60. 90.]

Tan function:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]

Inverse of tan:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]

In degrees:
[ 0. 30. 45. 60. 90.]

------------------------------
Functions for Rounding
numpy.around()
This is a function that returns the value rounded to the desired precision.
The function takes the following parameters.

numpy.around(a,decimals)
1
a

Input data

2
decimals

The number of decimals to round to. Default is 0. If negative, the integer


is rounded to position to the left of the
decimal point
-----------------------------------
import numpy as np
a = np.array([1.0,5.55, 123, 0.567, 25.532])
print('Original array:')
print(a)
print('\n')

print('After rounding:')
print(np.around(a))
print(np.around(a, decimals=1))

output:
Original array:
[ 1. 5.55 123. 0.567 25.532]
After rounding:
[ 1. 6. 123. 1. 26.]
[ 1. 5.6 123. 0.6 25.5]

-------------------------------------------
numpy.ceil()
The ceil() function returns the ceiling of an input value, i.e. the ceil of
the scalar x is the smallest integer i,
such that i >= x.
---------------------------------
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])

print('The given array:')


print(a)
print('\n')

print('The modified array:')


print(np.ceil(a))

output:
The given array:
[-1.7 1.5 -0.2 0.6 10. ]
The modified array:
[-1. 2. -0. 1. 10.]
-------------------------------------
numpy.floor()
This function returns the largest integer not greater than the input parameter.
The floor of the scalar x is the largest integer i, such that i <= x. Note
that in Python, flooring always is rounded away from 0.
----------------------------
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])
print('The given array:')
print(a)
print('\n')
print('The modified array:')
print(np.floor(a))

output:
The given array:
[-1.7 1.5 -0.2 0.6 10. ]

The modified array:


[-2. 1. -1. 0. 10.]

-------------------------------------
NumPy - Arithmetic Operations
Input arrays for performing arithmetic operations such as add(), subtract(),
multiply(), and divide() must be either of the same shape or should conform
to array broadcasting rules.
---------------------------------------
import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)
print('First array:')
print(a)
print('\n')
print('Second array:')
b = np.array([10,10,10])
print(b)
print('\n')

print('Add the two arrays:')


print(np.add(a, b))
print('\n')

print('Subtract the two arrays:')


print(np.subtract(a, b))
print('\n')

print('Multiply the two arrays:')


print(np.multiply(a, b))
print('\n')

print('Divide the two arrays:')


print(np.divide(a, b))

output:
First array:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]

Second array:
[10 10 10]

Add the two arrays:


[[10. 11. 12.]
[13. 14. 15.]
[16. 17. 18.]]

Subtract the two arrays:


[[-10. -9. -8.]
[ -7. -6. -5.]
[ -4. -3. -2.]]

Multiply the two arrays:


[[ 0. 10. 20.]
[30. 40. 50.]
[60. 70. 80.]]

-------------------------------------
numpy.reciprocal()
This function returns the reciprocal of argument, element-wise. For elements
with absolute values larger than 1, the result is always 0 because of the
way in which Python handles integer division. For integer 0, an overflow
warning is issued.
---------------------
import numpy as np
a = np.array([0.25, 1.33, 1, 0, 100])
print('Our array is:')
print(a)
print('\n')
print('After applying reciprocal function:')
print(np.reciprocal(a))
print('\n')

output:
Our array is:
[ 0.25 1.33 1. 0. 100. ]

After applying reciprocal function:


[4. 0.7518797 1. inf 0.01 ]

--------------------------
numpy.power()
This function treats elements in the first input array as base and returns
it raised to the power of the corresponding element in the second input array.
---------------------------------
import numpy as np
a = np.array([10,100,1000])
print('Our array is:')
print(a)
print('\n')
print('Applying power function:')
print(np.power(a, 2))
print('\n')

print('Second array:')
b = np.array([1,2,3])
print(b)
print('\n')

print('Applying power function again:')


print(np.power(a, b))

output:
Our array is:
[ 10 100 1000]

Applying power function:


[ 100 10000 1000000]

Second array:
[1 2 3]

Applying power function again:


[ 10 10000 1000000000]
--------------------------------
numpy.mod()
This function returns the remainder of division of the corresponding
elements in the input array. The function numpy.remainder() also produces
the same result.
-------------------------------
import numpy as np
a = np.array([10,20,30])
b = np.array([3,5,7])

print('First array:')
print(a)
print('\n')
print('Second array:')
print(b)
print('\n')

print('Applying mod() function:')


print(np.mod(a, b))
print('\n')

print('Applying remainder() function:')


print(np.remainder(a, b))

output:
First array:
[10 20 30]

Second array:
[3 5 7]

Applying mod() function:


[1 0 2]

Applying remainder() function:


[1 0 2]
------------------------------------
The following functions are used to perform operations on array with
complex numbers.

numpy.real() − returns the real part of the complex data type argument.

numpy.imag() − returns the imaginary part of the complex data type argument.

numpy.conj() − returns the complex conjugate, which is obtained by changing


the sign of the imaginary part.

numpy.angle() − returns the angle of the complex argument. The function has
degree parameter. If true, the angle in the degree is returned, otherwise
the angle is in radians.
---------------------------------------
import numpy as np
a = np.array([-5.6j, 0.2j, 11. , 1+1j])

print('Our array is:')


print(a)
print('\n')

print('Applying real() function:')


print(np.real(a))
print('\n')

print('Applying imag() function:')


print(np.imag(a))
print('\n')

print('Applying conj() function:')


print(np.conj(a))
print('\n')
print('Applying angle() function:')
print(np.angle(a))
print('\n')

print('Applying angle() function again (result in degrees)')


print(np.angle(a, deg=True))

output:
Our array is:
[-0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ]

Applying real() function:


[-0. 0. 11. 1.]

Applying imag() function:


[-5.6 0.2 0. 1. ]

Applying conj() function:


[-0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ]

Applying angle() function:


[-1.57079633 1.57079633 0. 0.78539816]

Applying angle() function again (result in degrees)


[-90. 90. 0. 45.]

---------------------------------
NumPy - Statistical Functions
NumPy has quite a few useful statistical functions for finding minimum,
maximum, percentile standard deviation and variance, etc. from the given
elements in the array. The functions are explained as follows −
numpy.amin() and numpy.amax()
These functions return the minimum and the maximum from the elements in the
given array along the specified axis.
--------------------------
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print('Our array is:')
print(a)
print('\n')
print('Applying amin() function:')
print(np.amin(a, 1))
print('\n')

print('Applying amin() function again:')


print(np.amin(a, 0))
print('\n')

print('Applying amax() function:')


print(np.amax(a))
print('\n')

print('Applying amax() function again:')


print(np.amax(a, axis=0))

output:
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]

Applying amin() function:


[3 3 2]

Applying amin() function again:


[2 4 3]

Applying amax() function:


9

Applying amax() function again:


[8 7 9]

Process finished with exit code 0

--------------
numpy.ptp()
The numpy.ptp() function returns the range (maximum-minimum) of values along
an axis.
numpy.ptp()function plays an important role in statistics by finding out
Range of given numbers. Range = max value – min value.
-------------------------------------------
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print('Our array is:')
print(a)
print('\n')

print('Applying ptp() function:')


print(np.ptp(a))
print('\n')

print('Applying ptp() function along axis 1:')


print(np.ptp(a, axis=1))
print('\n')

print('Applying ptp() function along axis 0:')


print(np.ptp(a, axis=0))

output:
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]

Applying ptp() function:


7

Applying ptp() function along axis 1:


[4 5 7]

Applying ptp() function along axis 0:


[6 3 6]

----------------------
numpy.percentile()
Percentile (or a centile) is a measure used in statistics indicating the value
below which a given percentage of observations in a group of observations fall.
The function numpy. percentile() takes the following arguments.
numpy.percentile(a, q, axis)
1
a

Input array

2
q

The percentile to compute must be between 0-100

3
axis

The axis along which the percentile is to be calculated


------------------------
import numpy as np
a = np.array([[30,40,70],[80,20,10],[50,90,60]])

print('Our array is:')


print(a)
print('\n')

print('Applying percentile() function:')


print(np.percentile(a, 50))
print('\n')

print('Applying percentile() function along axis 1:')


print(np.percentile(a, 50, axis=1))
print('\n')

print('Applying percentile() function along axis 0:')


print(np.percentile(a, 50, axis=0))

output:
Our array is:
[[30 40 70]
[80 20 10]
[50 90 60]]

Applying percentile() function:


50.0

Applying percentile() function along axis 1:


[40. 20. 60.]
Applying percentile() function along axis 0:
[50. 40. 60.]

-----------------------
numpy.median()

Median is defined as the value separating the higher half of a data sample
from the lower half.
----------------------------
import numpy as np
a = np.array([[30, 65, 70], [80, 95, 10], [50, 90, 60]])
print('Our array is:')
print(a)
print('\n')

print('Applying median() function:')


print(np.median(a))
print('\n')

print('Applying median() function along axis 0:')


print(np.median(a, axis=0))
print('\n')

print('Applying median() function along axis 1:')


print(np.median(a, axis=1))

output:
Our array is:
[[30 65 70]
[80 95 10]
[50 90 60]]

Applying median() function:


65.0

Applying median() function along axis 0:


[50. 90. 60.]

Applying median() function along axis 1:


[65. 80. 60.]
-----------------------
numpy.mean()
Arithmetic mean is the sum of elements along an axis divided by the number
of elements. The numpy.mean() function returns the arithmetic mean of elements
in the array. If the axis is mentioned, it is calculated along it.
-------------------------------------
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])

print('Our array is:')


print(a)
print('\n')

print('Applying mean() function:')


print(np.mean(a))
print('\n')
print('Applying mean() function along axis 0:')
print(np.mean(a, axis=0))
print('\n')

print('Applying mean() function along axis 1:')


print(np.mean(a, axis=1))

output:
Our array is:
[[1 2 3]
[3 4 5]
[4 5 6]]

Applying mean() function:


3.6666666666666665

Applying mean() function along axis 0:


[2.66666667 3.66666667 4.66666667]

Applying mean() function along axis 1:


[2. 4. 5.]

------------------------
numpy.average()
Weighted average is an average resulting from the multiplication of each
component by a factor reflecting its importance. The numpy.average()
function computes the weighted average of elements in an array according
to their respective weight given in another array. The function can have
an axis parameter. If the axis is not specified, the array is flattened.

Considering an array [1,2,3,4] and corresponding weights [4,3,2,1], the


weighted average is calculated by adding the product of the corresponding
elements and dividing the sum by the sum of weights.

Weighted average = (1*4+2*3+3*2+4*1)/(4+3+2+1)

import numpy as np
a = np.array([1,2,3,4])

print('Our array is:')


print(a)
print('\n')

print('Applying average() function:')


print(np.average(a))
print('\n')

# this is same as mean when weight is not specified


wts = np.array([4,3,2,1])

print('Applying average() function again:')


print(np.average(a, weights=wts))
print('\n')

# Returns the sum of weights, if the returned parameter is set to True.


print('Sum of weights')
print(np.average([1, 2, 3, 4], weights=[4, 3, 2, 1], returned=True))

output:
Our array is:
[1 2 3 4]

Applying average() function:


2.5

Applying average() function again:


2.0

Sum of weights
(2.0, 10.0)

--------------------------------
In a multi-dimensional array, the axis for computation can be specified.

import numpy as np
a = np.arange(6).reshape(3,2)
print('Our array is:')
print(a)
print('\n')

print('Modified array:')
wt = np.array([3,5])
print(np.average(a, axis=1, weights=wt))
print('\n')

print('Modified array:')
print(np.average(a, axis=1, weights=wt, returned=True))

output:
Our array is:
[[0 1]
[2 3]
[4 5]]

Modified array:
[0.625 2.625 4.625]

Modified array:
(array([0.625, 2.625, 4.625]), array([8., 8., 8.]))

-----------------------------------
Standard Deviation
Standard deviation is the square root of the average of squared deviations from
mean.
------------------------------------
import numpy as np
print(np.std([1, 2, 3, 4]))
output:
1.118033988749895
-------------------------------------
Variance
Variance is the average of squared deviations, i.e., mean(abs(x - x.mean())**2). In
other words,
the standard deviation is the square root of variance.
-----------------------------------
import numpy as np
print(np.var([1, 2, 3, 4]))

output:
1.25

----------------------------------------------------
NumPy - Sort, Search & Counting Functions
A variety of sorting related functions are available in NumPy. These sorting
functions implement different sorting algorithms, each of them characterized
by the speed of execution, worst case performance, the workspace required
and the stability of algorithms.
‘quicksort’
‘mergesort’
‘heapsort’
-----------------
numpy.sort()
The sort() function returns a sorted copy of the input array. It has the
following parameters −

numpy.sort(a, axis, kind, order)

1
a

Array to be sorted

2
axis

The axis along which the array is to be sorted. If none, the array is flattened,
sorting on the last axis

3
kind

Default is quicksort

4
order

If the array contains fields, the order of fields to be sorted


----------------------------------
import numpy as np
a = np.array([[3, 7], [9, 1]])
print('Our array is:')
print(a)
print('Applying sort() function:')
print(np.sort(a))
print('Sort along axis 0:')
print(np.sort(a, axis=0))
# Order parameter in sort function
dt = np.dtype([('name', 'S10'), ('age', int)])
a = np.array([("raju", 21), ("anil", 25), ("ravi", 17), ("amar", 27)], dtype=dt)
print('Our array is:')
print(a)

print('Order by name:')
print(np.sort(a, order='name'))

output:
Our array is:
[[3 7]
[9 1]]
Applying sort() function:
[[3 7]
[1 9]]
Sort along axis 0:
[[3 1]
[9 7]]
Our array is:
[(b'raju', 21) (b'anil', 25) (b'ravi', 17) (b'amar', 27)]
Order by name:
[(b'amar', 27) (b'anil', 25) (b'raju', 21) (b'ravi', 17)]
--------------------
numpy.argmax() and numpy.argmin()
These two functions return the indices of maximum and minimum elements
respectively along the given axis.
-------------------
import numpy as np
a = np.array([[30, 40, 70], [80, 20, 10], [50, 90, 60]])
print('Our array is:')
print(a)
print('\n')
print('Applying argmax() function:')
print(np.argmax(a))
print('\n')

print('Index of maximum number in flattened array')


print(a.flatten())
print('\n')

print('Array containing indices of maximum along axis 0:')


maxindex = np.argmax(a, axis=0)
print(maxindex)
print('\n')

print('Array containing indices of maximum along axis 1:')


maxindex = np.argmax(a, axis=1)
print(maxindex)
print('\n')

print('Applying argmin() function:')


minindex = np.argmin(a)
print(minindex)
print('\n')

print('Flattened array:')
print(a.flatten()[minindex])
print('\n')
print('Flattened array along axis 0:')
minindex = np.argmin(a, axis=0)
print(minindex)
print('\n')

print('Flattened array along axis 1:')


minindex = np.argmin(a, axis=1)
print(minindex)

output:
Our array is:
[[30 40 70]
[80 20 10]
[50 90 60]]

Applying argmax() function:


7

Index of maximum number in flattened array


[30 40 70 80 20 10 50 90 60]

Array containing indices of maximum along axis 0:


[1 2 0]

Array containing indices of maximum along axis 1:


[2 0 1]

Applying argmin() function:


5

Flattened array:
10

Flattened array along axis 0:


[0 1 1]

Flattened array along axis 1:


[0 2 0]

--------------
numpy.nonzero()
The numpy.nonzero() function returns the indices
of non-zero elements in the input array.
---------------------------------
import numpy as np
a = np.array([[30,40,0],[0,20,10],[50,0,60]])
print('Our array is:')
print(a)
print('\n')
print('Applying nonzero() function:')
print(np.nonzero(a))

Output:
ur array is:
[[30 40 0]
[ 0 20 10]
[50 0 60]]

Applying nonzero() function:


(array([0, 0, 1, 1, 2, 2], dtype=int64), array([0, 1, 1, 2, 0, 2], dtype=int64))
-----------------
numpy.where()
The where() function returns the indices of elements
in an input array where the given condition is satisfied.
-----------------
import numpy as np
x = np.arange(9.).reshape(3, 3)

print('Our array is:')


print(x)

print('Indices of elements > 3')


y = np.where(x > 3)
print(y)

print('Use these indices to get elements satisfying the condition')


print(x[y])

Output:
Our array is:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Indices of elements > 3
(array([1, 1, 2, 2, 2], dtype=int64), array([1, 2, 0, 1, 2], dtype=int64))
Use these indices to get elements satisfying the condition
[4. 5. 6. 7. 8.]

----------------------------
numpy.extract()
The extract() function returns the elements
satisfying any condition.
----------------------------------
import numpy as np
x = np.arange(9.).reshape(3, 3)
print('Our array is:')
print(x)

# define a condition
condition = np.mod(x,2) == 0

print('Element-wise value of condition')


print(condition)

print('Extract elements using condition')


print(np.extract(condition, x))

Output:
Our array is:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Element-wise value of condition
[[ True False True]
[False True False]
[ True False True]]
Extract elements using condition
[0. 2. 4. 6. 8.]

-------------------------------------
NumPy - Matrix Library
NumPy package contains a Matrix library numpy.matlib. This module has
functions that return matrices instead of ndarray
objects.
--------------------------------
matlib.empty()
The matlib.empty() function returns a new matrix without initializing
the entries. The function takes the following parameters.

numpy.matlib.empty(shape, dtype, order)

1
shape

int or tuple of int defining the shape of the new matrix

2
Dtype

Optional. Data type of the output

3
order

C or F
--------------------
import numpy.matlib
import numpy as np
print(np.matlib.empty((2, 2)))
# filled with random data

Output:
[[0. 0.]
[0. 0.]]

-----------------
numpy.matlib.zeros()
This function returns the matrix filled with zeros.
import numpy.matlib
import numpy as np
print(np.matlib.zeros((2,2)) )

output:
[[0. 0.]
[0. 0.]]

-----------
numpy.matlib.ones()
This function returns the matrix filled with 1s.
------------------------------
import numpy.matlib
import numpy as np
print (np.matlib.ones((2,2)))
Output:
[[1. 1.]
[1. 1.]]
-----------------------------------
numpy.matlib.eye()
This function returns a matrix with 1 along the diagonal elements
and the zeros elsewhere. The function takes the following parameters.
numpy.matlib.eye(n, M,k, dtype)
1
n

The number of rows in the resulting matrix

2
M

The number of columns, defaults to n

3
k

Index of diagonal

4
dtype

Data type of the output


----------------------------
import numpy.matlib
import numpy as np
print(np.matlib.eye(n=3, M=4, k=0, dtype=float))

Output:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
-----------------------
numpy.matlib.identity()
The numpy.matlib.identity() function returns the Identity matrix of
the given size. An identity matrix is a square matrix with all
diagonal elements as 1.
------------------------------
import numpy.matlib
import numpy as np
print (np.matlib.identity(5, dtype = float))

Output:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
-------------------------
numpy.matlib.rand()
The numpy.matlib.rand() function returns a matrix of the given size
filled with random values.
--------------------------------------
import numpy.matlib
import numpy as np
print(np.matlib.rand(3,3))

Output:
[[0.85187087 0.60435697 0.44439556]
[0.29060045 0.15376698 0.03306542]
[0.0488378 0.99729703 0.87463283]]
----------------------------
NumPy - Linear Algebra
NumPy package contains numpy.linalg module that
provides all the functionality
required for linear algebra.

numpy.dot()
This function returns the dot product of two arrays. For 2-D vectors, it is the
equivalent
to matrix multiplication. For 1-D arrays, it is the inner product of the vectors.
-----------------------------
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
print("Array a")
print(a)
print("Array b")
print(b)
print("Dot product")
print(np.dot(a,b))

#Note that the dot product is calculated as −

#[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]

Output:
Array a
[[1 2]
[3 4]]
Array b
[[11 12]
[13 14]]
Dot product
[[37 40]
[85 92]]

---------------------------------
numpy.vdot()
This function returns the dot product of the two vectors. If the first argument is
complex, then its conjugate is used for calculation. If the argument id is multi-
dimensional
array, it is flattened.

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
print("Array a:")
print(a)
print("Array b:")
print(b)
print("V dot product:")
print(np.vdot(a,b))
#Note − 1*11 + 2*12 + 3*13 + 4*14 = 130

Output:
Array a:
[[1 2]
[3 4]]
Array b:
[[11 12]
[13 14]]
V dot product:
130

------------------------------------------
numpy.inner()
This function returns the inner product of vectors for 1-D arrays. For higher
dimensions, it returns the sum product over the last axes.
--------------------------
import numpy as np
print (np.inner(np.array([1,2,3]),np.array([0,1,0])) )
# Equates to 1*0+2*1+3*0

Output:
2
-------------------------
numpy.matmul()
The numpy.matmul() function returns the matrix product of two arrays. While
it returns
a normal product for 2-D arrays
# For 2-D array, it is matrix multiplication
--------------------
import numpy as np

a = [[1,0],[0,1]]
b = [[4,1],[2,2]]
print("Matrix a")
print(a)
print("Matrix b")
print(b)
print("Result:")
print (np.matmul(a,b))

Output:
Matrix a
[[1, 0], [0, 1]]
Matrix b
[[4, 1], [2, 2]]
Result:
[[4 1]
[2 2]]
-----------------------------
NumPy - Determinant
Determinant is a very useful value in linear algebra. It calculated from the
diagonal
elements of a square matrix. For a 2x2 matrix, it is simply the subtraction of the
product of the top left and bottom right element from the product of other two.

In other words, for a matrix [[a,b], [c,d]], the determinant is computed as ‘ad-
bc’.
The larger square matrices are considered to be a combination of 2x2 matrices.
The numpy.linalg.det() function calculates the determinant of the input matrix.
-----------------------------------------
import numpy as np
a = np.array([[1,2], [3,4]])
print (np.linalg.det(a))

Output:
-2.0000000000000004
----------------------------------
numpy.linalg.solve()
The numpy.linalg.solve() function gives the solution of linear equations in the
matrix form.

Considering the following linear equations −

3x + 4y + 5z = 9

y + 2x+3z = 8

2x + 4y +5z = 7
------------------
# Program to show the working of solve()
import numpy as np

# creating the array "a"


A = np.array([[3, 4, 5], [1, 2, 3], [2, 4, 5]])
B = np.array([9, 8, 7])
print("Array A is: \n", A)
print("Array B is : \n", B)

# Calculating the equation


ans = np.linalg.solve(A, B)

# Printing the answer


print("Answer of the equation is :\n", ans)

# Checking if the answer if correct


print(np.allclose(np.dot(A, ans), B))

Output:
Array A is:
[[3 4 5]
[1 2 3]
[2 4 5]]
Array B is :
[9 8 7]
Answer of the equation is :
[ 2. -10.5 9. ]
True
---------------------------------
numpy.linalg.inv()
We use numpy.linalg.inv() function to calculate the
inverse of a matrix. The inverse of a matrix is such
that if it is multiplied by the original matrix, it
results in identity matrix.
---------------------------
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.linalg.inv(x)
print(x)
print(y)
print(np.dot(x, y))

output:
[[1 2]
[3 4]]
[[-2. 1. ]
[ 1.5 -0.5]]
[[1.00000000e+00 1.11022302e-16]
[0.00000000e+00 1.00000000e+00]]
---------------------------------

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy