Skip to main content

python numpy tutorial

NUMPY.APPEND () IN PYTHON:

v  This function adds values at the end of an input array as the name suggests, append means adding something.

v  The numpy.append() function is used to add or append new values to an existing numpy array. 

v  This function adds the new values at the end of the array.

 

SYNTAX:

numpy.append( arr, values, axis=None)  

                                                                                   

SAMPLE INPUT:

import numpy as np  

a=np.array([[123], [456], [789]])  

b=np.array([[102030], [405060], [708090]])  

c=np.append(a,b)  

c  

 

OUTPUT:

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 20, 30, 40, 50, 60, 70, 80,90])


NumPy Broadcasting

v  The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations

v   NumPy can perform such operations where the array of different shapes are involved.

Example

v  If we consider the matrix multiplication operation, if the shape of the two matrices is the same then this operation will be easily performed.

v  However, we may also need to operate if the shape is not similar.

Sample Input:

import numpy as np  

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

b = np.array([2,4,6,8,10,12,14])  

c = a*b;  

print(c)

Output:

[ 2 8 18 32 50 72 98]

 

NUMPY.ARRANGE() IN PYTHON:

v  It creates an array by using the evenly spaced values over the given interval. 

v  The interval mentioned is half opened i.e. [Start, Stop]).

v  NumPy arange() is one of the array creation routines based on numerical ranges

v   It creates an instance of ndarray with evenly spaced values and returns the reference to it.

 

SYNTAX:

 

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

 

PARAMETERS:

 

It accepts the following parameters.

  1. start: The starting of an interval. The default is 0.
  2. stop: represents the value at which the interval ends excluding this value.
  3. step: The number by which the interval values change.
  4. dtype: the data type of the numpy array items.

SAMPLE INPUT:

1.    import numpy as np  

2.    arr = np.arange(0,12,2,float)  

3.    print(arr)

 

OUTPUT:

[ 0. 2. 4. 6. 8.10]

 

 

 NUMPY.AVERAGE() IN PYTHON:

v  The numpy module of Python provides a function called numpy.

v  Average (), used for calculating the weighted average along the specified axis.

SYNTAX:

Numpy.average(a, axis=None, weights=None, returned=False)  

 

                                                                                   

SAMPLE INPUT:

 

import numpy as np  

data = list (range (1,7))  

output=np. average(data)  

data  

output  

 

OUTPUT:

 

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

 

3.5

 

 Numpy ceil()

v  This function returns the ceil value of the input array elements.

v  The floor of a number x is i if i is the smallest integer such that, i>=x.

 

Syntax:

numpy.ceil(array)  

Parameters:

array: Array elements whose ceil values are to be calculated.

                                                                                   

Sample Input:

import numpy as np  

arr = [0.23, 0.09, 1.2, 1.24, 9.90]  

print("Input array:",arr)  

r_arr = np.ceil(arr)  

print("Output array:",r_arr)  

arr2 = [145.23, 0.12, 12.34, 123]  

 r_arr2=np.ceil(arr2)  

 print("Input array:",arr2)  

 print("Output array:",r_arr2)  

 

Output:

Input array: [0.23, 0.09, 1.2, 1.24, 9.90]

Output array: [ 1.  1.  2.  2. 10.]

Input array: [145.26, 1.12, 13.34, 123]

Output array: [146.   2.  14. 123.]

 

NUMPY.CLIP() IN PYTHON

v  function is used to Clip (limit) the values in an array.

v  In the clip() function, we will pass the interval, and the values which are outside the interval will be clipped for the interval edges.

SYNTAX:

numpy.clip(a, a_min, a_max, out=None)  

                                                                                               

SAMPLE INPUT:

import numpy as np  

x= np.arange(12)  

y=np.clip(x, 311)  

y  

 

SAMPLE OUTPUT:

 

Array ([ 3, 3, 3, 3, 4, 5, 6, 7, 8, 9,10,11,11])

 

NUMPY CONCATENATE() IN PYTHON

v  The concatenate () function is a function from the NumPy package. This function essentially combines NumPy arrays together.

v  This function is basically used for joining two or more arrays of the same shape along a specified axis.

There are the following things which are essential to keep in mind:

v  NumPy's concatenate () is not like a traditional database join. It is like stacking NumPy arrays.

v  This function can operate both vertically and horizontally. This means we can concatenate arrays together horizontally or vertically.

The concatenate () function is usually written as np.concatenate(), but we can also write it as numpy.concatenate().

 

SYNTAX:

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

 

SAMPLE INPUT:

import numpy as np  

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

y=np.array([[12,30]])  

z=np.concatenate((x,y))  

z  

 

OUTPUT:

array([[ 1,  3],[ 2,  4],[12, 30]])


NUMPY.dot() in python:

v  The function is used to perform a product of two dot arrays.

v  If both the arrays 'a' and 'b' are 1-dimensional arrays, the dot() function performs the inner product of vectors (without complex conjugation).

v  If both the arrays 'a' and 'b' are 2-dimensional arrays, the dot() function performs the matrix multiplication. But for matrix multiplication use of matmul or 'a' @ 'b' is preferred.

v  If either 'a' or 'b' is 0-dimensional (scalar), the dot() function performs multiplication. Also, the use of numpy.multiply(a, b) or a *b method is preferred.

SYNTAX:

Numpy.dot(a,b,out=None)

                                                                                         

SAMPLE INPUT

import numpy as np  

a=np.dot(8,12)  

a  

 

OUTPUT:

96

 

 NUMPY FLOOR() IN  PYTHON:

v  This function returns the floor value of the input array elements. 

v  The floor of a number x is i if i is the largest integer such that, i<=x.

SYNTAX:

numpy.floor(array)

                                                                                   

SAMPLE INPUT:

import numpy as np

in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]

print ("Input array : \n", in_array)

floor off values = np.floor( in array)

print ("\n Rounded values : \n", floor off values)

in_array = [.53, 1.54, .71]

print ("\nInput array : \n", in_array)

flooroff_values = np.floor(in_array)

print ("\n Rounded values : \n", flooroff_values)

in_array = [.5538, 1.33354, .71445]

print ("\n Input array : \n", in_array)

flooroff_values = np.floor(in_array)

print ("\n Rounded values : \n", flooroff_values)

 

OUTPUT:

 

Input array:

 

[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

 

Rounded values:

 

[ 0.   1.   2.   3.   4.  10.]

 

Input array:

 

[0.53, 1.54, 0.71]

 

Rounded Values:

 

[ 0.  1.  0.]

Input array:

 

[0.5538, 1.33354, 0.71445]

 

Rounded Values:

 

[ 0.  1.  0.]

 

NUMPY.FROMBUFFER()

v  This function is used to create an array by using the specified buffer.

SYNTAX:

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

 

PARAMETERS  

It accepts the following parameters.

v  buffer: It represents an object that exposes a buffer interface.

v  dtype: It represents the data type of the returned data type array. The default value is 0.

v  count: It represents the length of the returned ndarray.

v  offset: It represents the starting position to read from. The default value is 0.

SAMPLE INPUT:

import numpy as np  

l = c'hello world'  

print(type(l))  

a = np.frombuffer(l, dtype = "S1")  

print(a)  

print(type(a))

 

OUTPUT:

 

[c'h' c'e' c'l' c'l' c'o' c' ' c'w' c'o' c'r' c'l' c'd']

 

 NUMPY HYPOT() METHOD:

v  This function is used to calculate the hypotenuse for the right angled triangle

v  The hypotenuse of the right angle is calculated as:

SYNTAX

numpy.hypot(array1, array2 out

PARAMETERS:

  1. array1: It is the input array of bases of the given right angled triangles.
  2. array2: It is the input array of perpendiculars of the given right angled triangles.
  3. Out: It is the shape of the output array.

SAMPLE INPUT:

import numpy as np  

base = [10,2,5,50]  

per= [3,10,23,6]  

print("Input base array:",base)  

print("Input perpendicular array:",per)  

hyp = np.hypot(base,per)  

print("hypotenuse ",hyp)  

 

OUTPUT:

Input base array: [10, 2, 5, 50]

Input perpendicular array: [3, 10, 23, 6]

hypotenuse[10.44030651 10.19803903 23.53720459 50.35871325]

 

 NUMPY.LINSPACE()

v  It is similar to the arrange function.

v  It only returns evenly separated values over a specified period.

v  The system implicitly calculates the step size.

SYNTAX:

numpy.linspace(start, stop, num, endpoint, retstep, dtype)

PARAMETERS:

It accepts the following parameters

v  start: It represents the starting value of the interval.

v  stop:It represents the stopping value of the interval.

v  num: The amount of evenly spaced samples over the interval to be generated. The default is 50.

v  endpoint: Its true value indicates that the stopping value is included in the interval.

v  rettstep: This has to be a boolean value. Represents the steps and samples between the consecutive numbers.

v  dtype: It represents the data type of the array items.

SAMPLE INPUT:

import numpy as np  

arr = np.linspace(10, 20, 5)  

print("The array over the given range is ",arr)  

 

OUTPUT:

The array over the given range is [10.  12.5 15.  17.5 20.]

 

 NUMPY.MATLIB.ONES()

v  This function is used to return a new matrix with the values initialized to ones.

SYNTAX:

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

PARAMETERS:

It accepts the following parameters.

v  shape: It is the Tuple defining the shape of the matrix.

v  dtype: It is the data type of the matrix.

v  order: It is the insertion order of the matrix.

SAMPLE INPUT:

import numpy as np    

import numpy.matlib    

print(numPy.matlib.ones((3,3)))   

 

OUPUT:

[[1. 1. 1.]

 [1. 1. 1.]

 [1. 1. 1.]]

 

 numpy.mean() in python

v  The sum of elements, along with an axis divided by the number of elements, is known as arithmetic mean.

v  The numpy.mean() function is used to compute the arithmetic mean along the specified axis.

v  This function returns the average of the array elements

v  By default, the average is taken on the flattened array. Else on the specified axis, float 64 is intermediate as well as return values are used for integer inputs

SYNTAX:

numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)

                                                                                   

SAMPLE CODE:

import numpy as np  

a = np.array([[12], [34]])  

b=np.mean(a)  

b  

x = np.array([[56], [734]])  

y=np.mean(x)  

y  

 

OUTPUT:

2.5

13.0

 

 

EXAMPLE 2:

 

import numpy as np  

a = np.array([[24], [35]])  

b=np.mean(a,axis=0)  

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

b  

c  

 

OUTPUT:

 

array([2.5, 4.5])

array([3., 4.])

 

 

 

 NUMPY.SAVE() IN PYTHON:

 

v  This module used to provide a numpy.save() function.

v  To extention an array into a binary file in .npy format

v  In many of the cases, we require data in binary format to manipulate it.

SYNTAX:

numpy.save(file, arr, allow_pickle=True, fix_imports=True)  

                                                                                               

SAMPLE INPUT:

import numpy as np  

from tempfile import TemporaryFile  

out_file = TemporaryFile()  

x=np.arange(16)  

np.save(out_file, x)  

_=out_file.seek(1) # Only needed here to simulate closing & reopening file  

np.load(outfile) 

 

OUTPUT:

 

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,15])


NUMPY STATISTICAL FUNCTIONS:

v  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. 

Function

NumPy

Min

np. min()

Max

np. max()

Mean

np. mean()

Median

np. median()

Standard deviation

np. std()

SAMPLE CODE:

 








SAMPLE INPUT:

 

Import NumPy as np

normal_ array=np. random. normal (5,0.5,10)

print (normal_ array)

 

OUTPUT:

[5.56171852 4.84233558 4.65392767 4.946659   4.85165567 5.61211317 4.46704244 5.22675736 4.49888936 4.68731125]

 

 

 

 

 

 

Example: Statistical function

### Min 
print (np. min(normal_ array))
 
### Max 
print (np. max(normal_ array)) 

 

### Mean 
print (np. mean(normal_ array))

 

### Median
print (np. median(normal_ array))

 

### Sd
print (np. std(normal_ array))

 

OUTPUT:

4.467042435266913
5.612113171990201
4.934841002270593
4.846995625786663
0.3875019367395316

 

 

 

 

 

 

 


Comments

Popular posts from this blog

Social Responsibililty

                                                                        SOCIAL RESPONSIBILITY Social Responsiblity   is an ethical framework and suggests that an entity, be it an organization or individual, has an obligation to act for the benefit of society at large.  Social responsibility  is a duty every individual has to perform so as to maintain a balance between the economy and the ecosystems.  4 Types of Social Responsibility Corporate Environmental Responsibility. ... Corporate Human Rights Responsibility. ... Corporate Philanthropic Responsibility. ... Corporate Economic Responsibility. Some of the common Responsibility for example given below: Reducing carbon footprints. Improving labor policies. Participating in fair trade. Charitable givin...

Online Education

ONLINE EDUCATION Online education is a flexible instructional delivery system that encompasses any kind of learning that takes place via the  Internet . Online learning gives educators an opportunity to reach students who may not be able to enroll in a traditional classroom course and supports students who need to work on their own schedule and at their own pace. The quantity of distance learning and online degrees in most disciplines is large and increasing rapidly. Schools and institutions that offer online learning are also increasing in number. Students pursuing degrees via the online approach must be selective to ensure that their coursework is done through a respected and credentialed institution. POSITIVE AND NEGATIVE EFFECTS OF LEARNING ONLINE Online education offers many positive benefits since students: have flexibility in taking classes and working at their own pace and time face no commuting or parking hassles learn to become responsible for their own education with in...

COVID-19 Drives Insurers to Revisit Actuarial Models

The COVID-19 pandemic has taken a huge toll on people and economies alike.  Governments and central banks worldwide have introduced a slew of fiscal measures to infuse liquidity and stability in the market.  However, in spite of these measures, the financial markets are expected to remain highly volatile for a significant duration, likely to worsen further due to lowering of interest rates and increasing credit spread gaps as well as risk of mortgage defaults.  Insurers therefore need to assess the impact on their solvency margins and IRRs, and re-assess the assumptions around mortality and morbidity rates, operational and financial costs, claims and losses, and so on.   Actuaries must review existing strategies and products and construct new ones to handle evolving risks and their interactions to be able to better model assets and liabilities as well as analyze asset and capital adequacies Moreover, insurers will have to perform strong scenario testing to identify k...