Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"


NumPy in DataScience:-
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

It is a predefined library of python which is used to perform a mathematical operation using predefined methods.

NumPy uses array-type data to perform the operation.

it contains array-type data to accept input data.


Operation using NumPy:-


Using NumPy, a developer can perform the following operations −
⦁    Mathematical and logical operations on arrays.
⦁    Fourier transforms and routines for shape manipulation.
⦁    Operations related to linear algebra. NumPy has in-built functions for linear algebra and random number generation.


What is the Difference between NumPy Array and List?

1)  Numpy array has n-th dimensional means it can be one dimension to nth dimension but the list has only 1 or 2 dimension approach.

2) Numpy array is used to contain data of data science to implement multiple functionalities of scipy, NumPy, pandas, and matplotlib but the list is used to provide python core functionality.

3) Numpy array speed and performance are best as compare to List.

4)  Numpy array space is fixed but the list is resizable.

5)  Numpy array can contain datatype and dimension attribute to store similar type of elements using proper sequence.



Q) Can we convert the list objects to NumPy array?

Answer)  Yes, we can convert the NumPy array to a list.

import numpy as np

arr = [10,20,30,70,11]
a = np.array(arr)
print(a)




How to install NumPy:-

before installation of NumPy python, pip, and python environment paths should be set.

open Command Prompt and Type:-

pip install NumPy

First, you should install the Jupyter notebook offline version or online version.

https://jupyter.org/try

Numpy array:-

It is called NDArray, which means we can create one-dimension,two-dimension, and multidimensional arrays using Numpy.

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


Display elements on NumPy Multidimensional Array?

a = np.array(([1,2],[3,4]))
for i in range(0,2):
    for j in range(0,2):
        print(a[i][j],end=' ')
    print()  


Assignments:-

1)  WAP to calculate the sum and multiply two different matrices using NumPy array?

2)  WAP to calculate Sum of row elements into NumPy array?

3)   WAP to display total prime elements into NumPy array?




Solve these assignments of NumPy array?

WAP to find max element in NumPy array?

WAP to sort the elements of the NumPy array?

WAP to split one array into two different subarrays?

WAP to merge two NumPy arrays into one array?

Solution of this program?

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
size= len(a)+len(b)
c = np.array([int]*size)
for i in range(0,size):
    if i<len(a):
        c[i]=a[i]
    else:
        c[i]=b[i-len(a)]
        
        
print(c)        

WAP to display prime elements in Numpy array



How many ways to declare NumPy array:-

1)  using NumPy array():-

    array() is used to convert list objects to NumPy array
    It is used to create a NumPy array using common type elements and specific elements both.
     
     arrayname =  numpy.array([elements,....],dtyle='datatype'])

    Example:-

    import numpy as np
    a = np.array([1,2,3,4,5])
    print(a)
    
2)  using numpy arange():-

  
    It is used to  create a NumPy array using starting and ending points with increment value

    arrayname = numpy.arange(start,end,increment)
    
  Example
 
  import numpy as np
  arr = np.arange(1,10,2,dtype='float')
  print(arr)


3)  using linspace():-

It is used to display elements based on the range with the same distance interval, distance will be calculated by starting value and ending value.

arrayname = numpy.linspace(start,end,increment)

import numpy as np
arr = np.linspace(1,10,5)
arr

4)  using empty():-

It is used to display random elements, we will provide a number of rows and columns using empty().
It will create random elements.


arrayname = numpy.empty((row,column),dtype='datatype')


import numpy as np
arr = np.empty((3,3),dtype='int')
arr


Numpy Operation:-

Numpy provides various predefined methods to manage array operation

1) ndmin:-  it is used to convert array to multiple dimension

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


2) dtype:-
  It is used to convert array elements to different types of elements.

a = np.array([1,2,3,4],dtype=complex)

3) shape:-  it will return a number of rows and column

print(a.shape) //


a complete example of NumPy:-

import numpy as np

#a = np.array([1,2,3,4],ndmin=2)
a = np.array([[1, 2], [3, 4]])
#a = np.array([1,2,3,4],dtype=complex)

print(a)
print(a.shape)

4) numpy.zeros():-  this method will create zero values array element

 import numpy as np
print(np.zeros((2,2)))


5) numpy.ones():-   this method will create one values array elements
 import numpy as np
print(np.ones((2,2)))


6) numpy.reshape():-  it is used to transpose the matrix or multi-dimension array.

   for example, if the matrix is 2*3 then it will convert into 3*2

   numpy.reshape(a, newShape, order='C')

import numpy as np
e  = np.array([(1,2,3), (4,5,6)])
print(e)
var = e.reshape(3,2)
print(var)
var=np.reshape(e,(3,2),order='C')
print(var)

7) flatten:-  It is used to display array in column style, Multi dimension array to single dimension array we will use flatten().

numpy.flatten(order='C')
 import numpy as np
e  = np.array([(1,2,3), (4,5,6)])
var=e.flatten() 
print(var)

8) hstack() and vstack():-

hstack():-  it is used to append array data horizontally and display results using a single dimension array.

a = np.array([1,2,3])
b = np.array([4,5,6])
c= numpy.hstack((a,b))

vstack():-  it is used to append array data vertically and display results into a multi-dimension array.

a = np.array([1,2,3])
b = np.array([4,5,6])
d = numpy.vstack((a,b))

Program to implement vstack and hstack:-

import numpy as np
a  = np.array([1,2,3])
b = np.array([4,7,8])
c = np.hstack((a,b))
d= np.hstack((a,b))

9) numpy.random.normal():-
  It is used to display random numbers based on start, distance, and last index.
numpy.random.normal(loc, scale, size)
Here
  • Loc: the mean. The center of distribution
  • scale: standard deviation.
  • Size: number of returns
## Generate random nmber from normal distribution
normal_array = np.random.normal(5, 0.5, 10)
print(normal_array)   
[5.56171852 4.84233558 4.65392767 4.946659   4.85165567 5.61211317 4.46704244 5.22675736 4.49888936 4.68731125]   


10) linspace():-  it is used to provide a sequence of data using starting point, ending point, and size.
     
      numpy.linspace(start, stop, size, endpoint)

It is used to subdivide the range data based on size


example of linespace():-

import numpy as np
a=np.linspace(0.0, 1.0, num=6)
print(a)
,........................................................................................................................

LogSpace

LogSpace returns even spaced numbers on a log scale. Logspace has the same parameters as np.linspace.

numpy.logspace(start, stop, num, endpoint)
 
import numpy as np
a=np.logspace(3, 4, num=3)
print(a)
 
it will provide 10**3 and 10**3.5 , 10**4   10 is the default base of log
 .................................................................
 
 

Indexing and slicing in Numpy:-

Indexing is used to display a particular element of the NumPy array.

slicing is the show data of a particular range

 
Q) WAP to display first row of numpy array?

import numpy as np
e  = np.array([(1,2,3), (4,5,6)])
print(e[0])
 
 
Another example of slicing :-
 Q)  Display Particular row in numpy array?
import numpy as np
e  = np.array([(1,2,3), (4,5,6)])
print(e[:2]) 
 
 Q)  Display numpy array elements using index array?
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
arr = x[np.array([1, 3, -3])]
print("\n Elements are : \n",arr)


Q)  Display numpy array elements using starting index, ending index and step
Syntax
arr[start:last:step]
Example of Display NumPy array using starting, ending and step's.
import numpy as np

arr = np.arange(20)
print(arr)
arr1 = arr[1:5:2]
print("\n Elements are : \n",arr1)


Advance Indexing:-


1)  Indexing by tuple index

We can fetch ndarray using paired index  So the index of the elements, in this case, are (0,0),(1,0),(2,1) and the corresponding elements are selected.

import numpy as np

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

print(a)    

print(a[[0 ,1 ,2 ],[0 ,0 ,1]])

2) Indexing by boolean:-

using this we can provide condition to fetch elements from numpy array.
arr = np.array([23,67,89,11,22])
print(arr[arr>60])  


1) How to read data from excel file ?


We can read data from excel file using two different module, xlrd openpyxl .
xlrd is only used to read .xlx file extension for old xlx file
openpyxl is used to read .xls and .xlsx both


1) Example to read xlx file using xlrd module.

import xlrd
 
# Give the location of the file
loc = ("d://covidnew.xls")
 
# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
 
# For row 0 and column 0
print(sheet.cell_value(0, 0))
print("Total no of rows is ",sheet.nrows)
print("Total no of columns is ",sheet.ncols)

data repository can be download by following link.  

https://github.com/shivaconceptsolution/repository

Now i am explaining another module openpyxl to read data from xlsx file.
pip install openpyxl

Complete Program Explanation to Read Data From openpyxl
Solution:-

from openpyxl import load_workbook
wb = load_workbook('d://covid.xlsx')

ws = wb.active

ar =[]   #Empty List

col = ws.max_column

ro = ws.max_row


for i in range(1,(ro+1)):
   k=0
   ar1=[]#Empty List
   for j in range(1,(col+1)):

       c1 = ws.cell(row = i, column = j)
       ar1.append(c1.value)
   k+=1
   ar.append(ar1)

print(ar)
#arr = np.concatenate((ar))
#arr1 = np.hstack((ar))# Joining Numpy Array using hstack().
#arr2 = np.vstack((ar))# Joining Numpy Array using vstack().




NumPy Statistical Functions with Example:-

 it is used to provide in-built() to implement statistical operation using min,max,deviation,variance,median,mean
 import numpy as np
normal_array = np.random.normal(5, 0.5, 10)
print(normal_array)  
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))
 

Another example of statistical function:-

import numpy as np
arr = np.array([23,11,78,11,90,160])
print(np.min(arr))
print(np.max(arr))
print(np.median(arr))
print(np.mean(arr))
print(np.std(arr))
print(np.average(arr))

arr= np.array([[1,23,78],[98,60,75],[79,25,48]])  
print(arr)
print(np.amax(arr),np.amin(arr))
a = np.array([20,20,20])  
print(a)  
print(np.percentile(a,10,0))

Assignements of Numpy Statistical functions:-

ASSIGNMENTS:-

create repository using excel file that contain

rno, name, branch, semester, total marks gender 
................................................................

1)  Display Record of max obtained marks student, Min obtained marks

2)  Display agreegate perecentage of male, female and all

3)  Display agreegate percentage of branch wise and all

4)  Display agreegate percetage using branch and semester

5)  max marks for each branch and semester for male , female and all


 ........................................................................
 
 
Numpy dot product in python:-
 
 
It is used to cross multiply matrix row element .
 
 
 
numpy.dot(x, y, out=None)
 
 
 
f = np.array([[1,2],[3,2]])
g = np.array([[1,2],[3,2]])
### 1*4+2*5
np.dot(f, g) 
 
 
NumPy Matmul():-  it is used to multiply matrix elements with row element to column elements.

h = [[1,2],[3,4]]
i = [[5,6],[7,8]]
### 1*5+2*7 = 19
np.matmul(h, i)
 

Determinant

Last but not least, if you need to compute the determinant, you can use np.linalg.det(). Note that numpy takes care of the dimension.
## Determinant 2*2 matrix ###

 i = [[5,6],[7,8]]

        5*8-7*6

np.linalg.det(i)
 
 
 np.linalg.matrix_rank(A)):-  It return number of columns in matrix 

 np.trace(A))  :-  It return sum of main diagonal of matrix

print(np.linalg.det(A)) :-  It return determinant of matrix   
print(np.linalg.inv(A)) :-   It provide inverse of matrix
print( np.linalg.matrix_power(A, 3))  :-  It provide power of current element and perform addition of remaining column elements.


Example of Determinant Formular:-

import numpy as np
 
A = np.array([[2, 1, 1,4],
              [4, -2, 5,5],
              [2, 8, 7,5],
              [2, 8, 7,3]])
 
print(np.linalg.matrix_rank(A))

print(np.trace(A))
print(np.linalg.det(A))
print(np.linalg.inv(A))
print( np.linalg.matrix_power(A, 3))



Numpy Eigen Function Example:-

This function is used to return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix.

eigh():-  Returns two objects, a 1-D array containing the eigenvalues of a matrix, and a 2-D square array or matrix (depending on the input type) of the corresponding eigenvectors (in columns). 

from numpy import linalg as scs

c, d = scs.eigh(a)

print("Eigen value is :", c)
print("Eigen vector  is :", d)

numpy.linalg.eig(a)

This function is used to compute the eigenvalues and right eigenvectors of a square array.

import numpy as np
from numpy import linalg as scs

a = np.diag((1, 2, 3))
print("Array is :",a)

# calculating an eigenvalue
# using eig() function
c, d = scs.eig(a)
print("Eigen value is :",c)
print("Eigen vector is :",d)


Numpy DateTime Function:-

var = np.datetime64('2017-02-12')
...........................................................................

How to get the difference between two dates using NumPy?

import numpy as np
import datetime
from datetime import date
curdate = np.datetime64(datetime.datetime.now())
print(curdate)
dob = np.datetime64('2017-02-12')
ms=curdate-dob
print(np.timedelta64(ms,'D'))    

How to get the difference between two dates using Python?

today = datetime.date.today()
f_date = date(2014, 7, 2)
l_date = date(2021, 1, 1)
delta = today - l_date
print(delta.days)




ASSIGNMENT:-

CONVERT JSON FILE TO NUMPY ARRAY?

CONVERT REMOTE JSON https://shivaconceptsolution.com/webservices/showreg.php to NUMPY ARRAY?


CONVERT CSV TO ARRAY?


NUMPY Predefine Array?

all()
any()
take()
put()
apply_along_axis()
apply_over_axes()
argmin()
argmax()
nanargmin()
nanargmax()
amax()
amin()
insert()
delete()
append()
around()
flip()
fliplr()
flipud()
triu()
tril()
tri()
empty()
empty_like()
zeros()
zeros_like()
ones()
ones_like()
full_like()
diag()
diagflat()
diag_indices()
asmatrix()
bmat()
eye()
roll()
identity()
arange()
place()
extract()
compress()
rot90()
tile()
reshape()
ravel()
isinf()
isrealobj()
isscalar()
isneginf()
isposinf()
iscomplex()
isnan()
iscomplexobj()
isreal()
isfinite()
isfortran()
exp()
exp2()
fix()
hypot()
absolute()
ceil()
floor()
degrees()
radians()
npv()
fv()
pv()
power()
float_power()
log()
log1()
log2()
log10()
dot()
vdot()
trunc()
divide()
floor_divide()
true_divide()
random.rand()
random.randn()
ndarray.flat()
expm1()
bincount()
rint()
equal()
not_equal()
less()
less_equal()
greater()
greater_equal()
prod()
square()
cbrt()
logical_or()
logical_and()
logical_not()
logical_xor()
array_equal()
array_equiv()
sin()
cos()
tan()
sinh()
cosh()
tanh()
arcsin()
arccos()
arctan()
arctan2()



Assignments of the Numpy Array?

MOST Important Array Interview Questions for Interview?

Level 1:-


Check if a key is present in every segment of size k in an array?

Find the minimum and maximum element in an array

Write a program to reverse the array

Write a program to sort the given array

Find the Kth largest and Kth smallest number in an array


Find the occurrence of an integer in the array

Sort the array of 0s, 1s, and 2s

Range and Coefficient of array

Move all the negative elements to one side of the array

Find the Union and Intersection of the two sorted arrays

Level 2

Write a program to cyclically rotate an array by one

Find the missing integer

Count Pairs with given sum

Find duplicates in an array

Sort an Array using the Quicksort algorithm

Find common elements in three sorted arrays

Find the first repeating element in an array of integers

Find the first non-repeating element in a given array of integers

Find the largest three elements in an array Time

Rearrange the array in alternating positive and negative items

Find if there is any subarray with sum equal to zero

Find Largest sum contiguous Subarray

Find the factorial of a large number

Find Maximum Product Subarray

Find longest consecutive subsequence

Find the minimum element in a rotated and sorted array

Find all elements that appear more than N/K times

GCD of given index ranges in an array

Minimize the maximum difference between the heights

Minimum number of jumps to reach the end

Find the two repetitive elements in a given array

Find a triplet that sums to a given value

Construct a N*M matrix from the user input

Find the row with the maximum number of 1’s

Print the matrix in a Spiral manner

Find whether an array is a subset of another array

Implement two Stacks in an array

Majority Element

Wave Array

Trapping Rainwater

Level 3

Maximum Index

Max sum path in two arrays

Find Missing And Repeating

Stock buy and sell Problem

Pair with given sum in a sorted array

Chocolate Distribution Problem

Longest Consecutive Subsequence

Print all possible combinations of r elements in a given array







39 Comments

If you have any doubt in programming or join online classes then you can contact us by comment .

  1. Convert Excel data to Numpy Array and display in flatten pattern?


    Create 10 students percentage into two different excel sheet and merge them using hstack and vstack()

    ReplyDelete
  2. # DATA SCIENCE ( 6 to 7 PM BATCH)
    # CODE To Convert Excel data to Numpy Array and Display in Flatten Pattern.
    #Stacking Along Rows(hstack())
    #Stacking Along Columns(vstack())


    import numpy as np

    import openpyxl

    from openpyxl import Workbook # Call a Workbook() function of openpyxl
    wb = Workbook() # to create a new blank Workbook object

    # Get workbook active sheet
    # from the active attribute.
    ws = wb.active

    ws.title = "Student's Record" # One can change the name of the title

    s = [['Student Name','Age','DOB',"Roll. No.","Maximum Age"],["ROHIT",40,"21-08-1980",123],["KUMAR",30,"15-09-1990",45]]

    ar =[]#Empty List


    for i in range(0,len(s)):
    k=0
    ar1=[]#Empty List
    for j in range(1,len(s[1])+1):

    c1 = ws.cell(row = i+1, column = j)
    c1.value=s[i][k]# writing values to cells

    ar1.append(c1.value)
    k+=1
    ar.append(ar1)
    arr = np.concatenate((ar))# Joining Numpy Array using mconcatenate() function.
    arr1 = np.hstack((ar))# Joining Numpy Array using hstack().
    arr2 = np.vstack((ar))# Joining Numpy Array using vstack().



    wb.save(filename = 'excel_array.xlsx')


    print("Numpy Array :-")
    print(arr,"\n","arr1\n",arr1,"\n","arr2\n",arr2)

    ReplyDelete
  3. # CODE To Convert Excel data to Numpy Array and Display in Flatten Pattern Using Concatenate() Function
    # Excel data to Numpy Array Using Stacking Along Columns
    # Excel data to Numpy Array Using Stacking Along Rows

    import openpyxl
    from openpyxl import load_workbook
    wb = openpyxl.load_workbook('sample_book.xlsx')


    ws = wb.active

    ar =[]#Empty List

    col = ws.max_column

    ro = ws.max_row


    for i in range(1,(ro+1)):
    k=0
    ar1=[]#Empty List
    for j in range(1,(col+1)):

    c1 = ws.cell(row = i, column = j)

    ar1.append(c1.value)
    k+=1
    ar.append(ar1)
    arr = np.concatenate((ar))
    arr1 = np.hstack((ar))# Joining Numpy Array using hstack().
    arr2 = np.vstack((ar))# Joining Numpy Array using vstack().




    print("Numpy Array :-")
    print(arr,"\n","arr1\n",arr1,"\n","arr2\n",arr2)

    ReplyDelete
  4. # CODE To Merge two different excel sheet using hstack() and vstack()

    import openpyxl
    from openpyxl import load_workbook
    wb = openpyxl.load_workbook('sample_book.xlsx')
    wa = openpyxl.load_workbook('excel_array.xlsx')


    ws = wb.active
    we = wa.active

    ar =[]#Empty List
    ae = []

    col = ws.max_column

    ro = ws.max_row


    for i in range(1,(ro+1)):
    k=0
    ar1=[]#Empty List
    ae1 = []
    for j in range(1,(col+1)):

    c1 = ws.cell(row = i, column = j)
    c2 = we.cell(row = i+1, column = j)

    ar1.append(c1.value)
    ae1.append(c2.value)
    k+=1

    ar.append(ar1)
    ae.append(ae1)
    arr1 = np.hstack((ar,ae))# Joining Numpy Array using hstack().
    arr2 = np.vstack((ar,ae))# Joining Numpy Array using vstack().




    print("Numpy Array :-")
    print("\n","arr1\n","\n",arr1,"\n","\n","arr2\n","\n",arr2)

    ReplyDelete
  5. # CODE To Merge two different excel sheet using hstack() and vstack()

    import openpyxl
    import numpy as np
    from openpyxl import load_workbook
    wb = openpyxl.load_workbook('Record.xlsx')
    wa = openpyxl.load_workbook('Book1.xlsx')

    ws = wb.active# for workbook 1
    we = wa.active# for workbook 2

    ar =[]#Empty List
    ae = []

    col = ws.max_column

    ro = ws.max_row


    for i in range(1,(ro+1)):
    k=0
    ar1=[]#Empty List
    ae1 = []
    for j in range(1,(col+1)):
    c1 = ws.cell(row = i, column = j)
    c2 = we.cell(row = i+1, column = j)
    ar1.append(c1.value)
    ae1.append(c2.value)
    k+=1
    ar.append(ar1)
    ae.append(ae1)


    arr1 = np.hstack((ar,ae))# Joining Numpy Array using hstack().
    arr2 = np.vstack((ar,ae))# Joining Numpy Array using vstack().


    print("Numpy Array :-")
    print("\n","Arr1 Value\n","\n",arr1,"\n","\n","Arr2 Value\n","\n",arr2)

    ReplyDelete
  6. # CODE To Convert Excel data to Numpy Array and Display in Flatten Pattern Using Concatenate() Function


    import openpyxl
    import numpy as np
    from openpyxl import load_workbook
    wb = openpyxl.load_workbook('Record.xlsx')
    ws = wb.active
    ar =[]#Empty List
    col = ws.max_column
    ro = ws.max_row


    for i in range(1,(ro+1)):
    k=0
    ar1=[]#Empty List
    for j in range(1,(col+1)):
    c1 = ws.cell(row = i, column = j)
    ar1.append(c1.value)
    k+=1
    ar.append(ar1)
    arr = np.concatenate((ar))

    arr1 = np.hstack((ar))# Joining Numpy Array using hstack().
    arr2 = np.vstack((ar))# Joining Numpy Array using vstack().




    print("Numpy Array :-")
    print(arr,"\n","arr1\n",arr1,"\n","arr2\n",arr2)

    # Excel data to Numpy Array Using Stacking Along Columns
    # Excel data to Numpy Array Using Stacking Along Rows

    ReplyDelete
    Replies
    1. It throws error
      because concatenate function takes two array (or more than two) as argument and axis.

      Delete

  7. # Data Science (6 to 7 PM BATCH)

    # CONVERT REMOTE JSON https://shivaconceptsolution.com/webservices/showreg.php to NUMPY ARRAY.


    import json
    import urllib
    import numpy as np


    url = "https://shivaconceptsolution.com/webservices/showreg.php"
    # open a connection to a URL using urllib
    json_url = urllib.request.urlopen(url)


    # parse json object
    data = json.loads(json_url.read())

    # here we create new data_file.json file with write mode using file i/o operation
    with open("Sample1.txt", "w") as p:
    # write json data into file
    json.dump(data, p)


    # Opening JSON file with read mode.
    with open("Sample1.txt", "r") as p:

    # Reading from file and returns JSON object as a dictionary
    data = json.load(p)

    # Closing file
    p.close()

    print(type(data))

    # Pretty Printing JSON string back
    #print(json.dumps(data,indent=4,sort_keys=True))

    for p_id, p_info in data.items():
    print( p_id,"\n")

    for key in p_info:

    # to return a group of the key-value
    # pairs in the dictionary
    result = key.items()

    # Convert object to a list
    data = list(result)

    # Convert list to an array
    numpyArray = np.array(data)

    # print the numpy array
    print(numpyArray)


    print(len(numpyArray))
    print(type(numpyArray))

    ReplyDelete
  8. # Data Science (6 to 7 PM BATCH)

    # Program to CONVERT CSV TO ARRAY.

    import csv #Import the csv library.
    import numpy as np

    # With the file open, create a new csv.reader object.
    with open('data3.csv', 'r') as f:

    #Pass in the keyword argument delimiter=";" to make sure that the records are
    # split up on the semicolon character instead of the default comma character.
    wines = list(csv.reader(f, delimiter=';'))


    ## Here We get a LIST (wines)
    print("\n\n",type(wines),"\n\n",wines)

    wines1 = np.array(wines)


    # List Slicing.(wines[1:])
    # Specify the keyword argument dtype( dtype=np.str) to make sure each element is converted to a String.
    wines = np.array(wines[1:], dtype=np.str)

    # we’ll now get a NumPy array
    print()
    print(type(wines),"\nNumPy array\n",wines,"\n\n",type(wines1),"\nNumPy array 1\n",wines1)

    ReplyDelete
  9. #Convert CSV to Numpy Array
    import csv

    results = []
    with open("data3.csv") as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats
    for row in reader: # each row is a list
    results.append(row)
    print(results)

    ReplyDelete
  10. # Basic Methods And Function of numpy

    import numpy as np
    a=np.array([1,2,3])
    print(a[1])
    print(a.ndim) #it will print the type of array here one dimensional array.

    a=np.array([[1,2],[2,3],[3,4]])
    print(a.ndim) # it will print the type of array here two dimensional array.
    print(a.itemsize) # it will print the size of an datatype means if int in python the it will print 4
    print(a.dtype) # it will print the type of datatype
    print("Min: ",a.min())# it will print the minimum element of array
    print("Max: ",a.max())# it will print the maximum element of array

    a=np.array([[1,2],[7,3],[5,4]],dtype=np.float64)
    print(a.dtype)
    print(a.size)# it will print the total elements in array
    print(a.itemsize)# output 8 because float64 contain 8 bits
    print(a.shape) # it will print the dimensions of array (rows=3,column=2)
    print(a.reshape(2,3))
    print(a.ravel())# it will print the array in flatten format (straight row) convert into one dimension

    a=np.array([[1,2],[2,3],[3,4]],dtype=complex)# it will print the array into complex numbers
    print(a)

    print(np.zeros((3,4)))# it will create an array of zeros of dimensional 3 rows and 4 column
    print(np.ones((3,4)))


    l=range(5)# it will create a list (of numbers 0 to 4)for Example 0,1,2,3,4
    print(l)
    print(l[0])
    print(l[1])
    # OR similar to numpy array using arange function
    print(np.arange(1,5))# it will create an array of range 1 to 4 elements
    print(np.arange(1,5,2))# it will print 1,3 because 2 is the steps taken to jump


    print(np.linspace(1,5,10))# 10 is the number of total counts betwoon 1 to 5
    print(np.linspace(1,5,5))


    a=np.array([[1,2],[3,4],[5,6]])
    print("Sum: ",a.sum())# it will print the sum of array elements.
    print(a.sum(axis=0))# here Axis=0 means coloumn sum
    print(a.sum(axis=1))# here Axis=0 means Rows sum
    print("\n Square Root of Elements:\n",np.sqrt(a))# here square root of the numbers.
    print("Standard Devatation of array of whole arrar elements: ",np.std(a))


    a=np.array([[1,2],[3,4]])
    b=np.array([[5,6],[7,8]])
    print("Addition: \n",a+b)# it will print the addition of both the array all mathematical operation (+,-,*,/)
    print("Matrix Product: \n",a.dot(b))# it will print the matrix product of this two indidual array elements










    print(np.arange(1,5,2))# it will print 1,3 because 2 is the steps taken to jump

    ReplyDelete
  11. #Slicing in array
    import numpy as np

    n=[6,7,8]# list slicing
    print(n[0:2])# it will print 6,7 because 0 is the starting position and 2 is number of elements(0+1)
    #no of element is 2 so 6,7 return
    print(n[-1])# it will print the last element

    a=np.array([6,7,8])# numpy array slicing
    print(a[0:2])# print same in numpy array
    print(a[-1])# print 8

    a=np.array([[6,7,8],[1,2,3],[9,3,2]]) # multidimensional array
    print(a[1,2])# it will print 3 because 1 is a row and 2 is the coulmn
    print(a[0:2,2])# it will print 8 and 3 because 0 is not included
    print(a[-1])# print last array
    print(a[-1,0:2])
    print(a[:,1:3])# because (:) is for all the rows the and we want to print only 2 and 3 coulmn so 1: 3 means 0,1,2 totals
    #total is 3 coulmn so 1:3 is for 1 st column and 3 rd column

    a=np.array([[6,7,8],[1,2,3],[9,3,2]]) # multidimensional array
    for row in a:
    print(row)
    print(type(row)) # this is also ndarray


    for cell in a.flat:
    print(cell)# it will print in flatten form


    ReplyDelete
  12. # STACKING

    # arange is used to create a dynamic array with range 6(0,1,2,3,4,5) and
    # reshape is a method to print in dimension3 rows and 2 column
    a=np.arange(6).reshape(3,2)
    b=np.arange(6,12).reshape(3,2)
    print("\n",a)
    print("\n",b)

    print("\n",np.vstack((a,b)))# print in vertical format and combine both the arrays
    print("\n",np.hstack((a,b)))# print in horizontal format


    a=np.arange(30).reshape(2,15)
    print(a)
    print("\n Split array in three equal format:",np.hsplit(a,3))# here 3 is the number of peice you have to cut this original array (a)
    # this is same for (VERTICAL SPLIT) also np.vsplit(a,2)
    res=np.hsplit(a,3)
    print("\n 1st array:\n",res[0])
    print("\n 2nd array:\n",res[1])
    print("\n 3rd array:\n",res[2])

    ReplyDelete
  13. # Boolean Arrays


    a=np.arange(12).reshape(3,4)
    print(a)
    b = a>4
    print(b)
    print(type(b))
    print(a[b])# in this whenever b found True print the original value into the a array
    # a[b]=-1 # if b found true they replace the value if true with -1

    ReplyDelete
  14. # Iterating array


    a=np.arange(12).reshape(3,4)
    print(a)

    '''
    for row in a:
    for cell in row:# used to flatten the array
    print(cell)
    '''
    # OR
    '''
    for cell in a.flatten():
    print(cell)
    '''
    # OR


    for cell in np.nditer(a,order='C'):# it will print same as flatten id you use 'C'.
    print(cell)
    '''
    The Order 'C' means rows wise printing means 0,1,2,3,4,5,6,7....and so on...
    and
    the Order 'F' means forton column wise printing means 0,4,8,1,5,9,2,6,10.....so on..
    '''

    for x in np.nditer(a,order='F',flags=['external_loop']): # print each column seprate of Forton Order
    print("\nSeprate each Column \n",x)

    ReplyDelete
  15. # Modify Elements of Array


    a=np.arange(12).reshape(3,4)
    print(a)

    for x in np.nditer(a,op_flags=['readwrite']):
    x[...]=x*x # means that square each elements of array
    print(a)

    # for additing both these array into one .
    b=np.arange(3,15,4).reshape(3,1)
    print(b)

    print("\nCombine Both The arrya")
    for x,y in np.nditer([a,b]):
    print(x,y)

    ReplyDelete
  16. #Statitics Operation
    #Reading Data From The Excel File

    #Two worksheet
    #worksheet= A
    #worksheet= B

    import openpyxl
    import numpy as np

    l1 = 0
    l2 = 1
    wb = openpyxl.load_workbook('Record.xlsx')
    sheets = wb.sheetnames
    ws = wb[sheets[l1]]
    print(ws)
    ws1 = wb[sheets[l2]]
    print(ws1)

    print("\n\nSheet 1 Data \n")
    ar =[]#Empty List
    col = ws.max_column
    ro = ws.max_row
    for i in range(1,(ro+1)):
    k=0
    ar1=[]#Empty List
    for j in range(1,(col+1)):
    c1 = ws.cell(row = i, column = j)
    ar1.append(c1.value)
    k+=1
    ar.append(ar1)
    arr = np.concatenate((ar))
    print(arr)
    print("\n")

    print("Sheet 2 Data \n")

    a =[]#Empty List
    col1 = ws1.max_column
    ro1 = ws1.max_row

    for k in range(1,(ro1+1)):
    k1=0
    ar2=[]#Empty List
    for p in range(1,(col1+1)):
    c12 = ws1.cell(row = k, column = p)
    ar2.append(c12.value)
    k1+=1
    a.append(ar2)
    arrr = np.concatenate((a))
    print(arrr)


    #Basic statistics Operation
    import statistics as st
    wb = openpyxl.load_workbook('Record.xlsx', data_only=True)
    ws = wb.active
    list1 = []
    ro = ws.max_row

    for k in range(len(wb.sheetnames)):
    wb.active = k
    ws = wb.active

    for i in range(0,ro-1):
    val = ws.cell(row = 2+i, column = 5)
    list1.append(val.value)

    print("Number of Total values: {0}".format(len(list1)))
    print("Sum of Total values: {0}".format(sum(list1)))
    print("Minimum value in the table: {0}".format(min(list1)))
    print("Maximum value in the table: {0}".format(max(list1)))
    print("Mean: {0}".format(st.mean(list1)))
    print("Median: {0}".format(st.median(list1)))
    print("Standard deviation: {0}".format(st.stdev(list1)))

    ReplyDelete
  17. import numpy as np
    def max (ar):
    max=0
    for i in ar:
    if max<i:
    max=i
    return max
    ar=np.array([10,96,30,40])
    s=max(ar)
    print(s)

    ReplyDelete
  18. import numpy as np
    num=np.array([1,2,3,5,4])
    a=2
    count=0
    for i in num:
    while a<i:
    if i%a==0:
    count=count+1
    break
    a=a+1
    if count==0:
    print("prime:",i)
    else:
    print("not prime:",i)

    ReplyDelete
  19. #Find the minimum and maximum element in an array
    l=[]
    n=int(input("enter the length of array:="))
    for i in range(0,n):
    num=int(input("enter the elements:-"))
    l.append(num)
    arr=np.array(l)
    m=arr[0]
    mi=arr[0]
    for i in range(0,n):

    if arr[i]>m:
    m=arr[i]
    for i in range(0,n):

    if arr[i]<mi:
    mi=arr[i]
    print("max is:-",m,"min is:-",mi)

    ReplyDelete
  20. #Write a program to reverse the array

    arr=np.array([1,2,3,6,59,8,2,3,6])
    for i in range(len(arr)-1,-1,-1):
    print(arr[i])
    type(arr)

    ReplyDelete
  21. #Write a program to reverse the array

    arr=np.array([1,2,3,6,59,8,2,3,6])
    for i in range(len(arr)-1,-1,-1):
    print(arr[i])
    type(arr)

    ReplyDelete
  22. #Write a program to sort the given array
    arr=np.array([1,9,6,3,85,96,32,321])
    for i in range(0,len(arr)):
    for j in range(0,len(arr)):
    if arr[i]<arr[j]:
    arr[i],arr[j]=arr[j],arr[i]
    arr

    ReplyDelete
  23. #Find the Kth largest and Kth smallest number in an array
    arr=np.array([1,9,6,3,7,5,3,4,12,36,98,74,52,20,30,98])
    for i in range(0,len(arr)):
    for j in range(0,len(arr)):
    if arr[i]<arr[j]:
    arr[i],arr[j]=arr[j],arr[i]
    small=int(input("smallest number"))
    print(arr[small-1])
    large=int(input("largest number"))
    print(arr[-large])

    ReplyDelete
  24. #Find the occurrence of an integer in the array
    l=[]
    num=int(input("enter number:-"))
    while num>0:
    a=num%10
    l.append(a)
    arr=np.array(l)
    num=num//10
    for i in range(0,10):
    count=0
    for j in range(0,len(arr)):
    if i==arr[j]:
    count+=1
    print("number ",i," repeated ",count)

    ReplyDelete
  25. #Sort the array of 0s, 1s, and 2s
    arr=np.array([1,0,2,0,1,0,2,0,1,2,2,2,0,1,0,2,0,1,0,2])
    low=0
    mid=0
    high=len(arr)-1
    while mid<=high:
    if arr[mid]==0:
    arr[low],arr[mid]=arr[mid],arr[low]
    mid+=1
    low+=1
    elif arr[mid]==1:
    mid+=1
    else:
    arr[high],arr[mid]=arr[mid],arr[high]
    high-=1
    arr

    ReplyDelete
  26. #Range and Coefficient of array
    arr=np.array([5,10,9,6,8,12,15])
    mx=arr[0]
    mn=arr[0]
    for i in range(0,len(arr)):
    if arr[i]>mx:
    mx=arr[i]
    if arr[i]<mn:
    mn=arr[i]
    r=mx-mn
    print("range of array is:-",r)
    r1=mx+mn
    c=r/r1
    print("coefficient of array is:-",c)

    ReplyDelete
  27. #Move all the negative elements to one side of the array
    arr=np.array([9,6,3,-8,-1,-7,-6,-4,10])
    j=0
    for i in range(0,len(arr)):
    if arr[i]<0:
    arr[i],arr[j]=arr[j],arr[i]
    j+=1
    arr

    ReplyDelete
  28. #Find the Union and Intersection of the two sorted arrays
    arr1=np.array([1,3,4,6,8,9])
    arr2=np.array([4,6,7,9,10,15])
    size=len(arr1)+len(arr2)
    arr3=np.array([int]*size)
    s=[]
    for i in range(0,size):
    if i<len(arr1):
    arr3[i]=arr1[i]
    else:
    arr3[i]=arr2[i-len(arr1)]
    a=set(arr3)
    m=np.array([a])
    print("union is:-",m)
    for i in range(0,len(arr1)):
    for j in range(0,len(arr2)):
    if arr1[i]==arr2[j]:
    s.append(arr1[i])
    print("intersection is:-",np.array(s))

    ReplyDelete
  29. #Write a program to cyclically rotate an array by one
    arr=np.array([1,5,9,3,5,9,6,2,6,8,4,14,5])
    j=0
    for i in range(0,len(arr)):
    arr[i],arr[j]=arr[j],arr[i]
    arr

    ReplyDelete
  30. #Find the missing integer
    arr=np.array([1,9,6,3,7,15,5])
    mx=arr[0]
    mn=arr[0]
    for i in range(0,len(arr)):
    if arr[i]>mx:
    mx=arr[i]
    if arr[i]<mn:
    mn=arr[i]
    for i in range(mn,mx):
    if i not in arr:
    print(i)

    ReplyDelete
  31. #Count Pairs with given sum
    arr=np.array([1, 5, 7, -1, 5])
    sum=6
    count=0
    for i in range(0,len(arr)):
    for j in range(i+1,len(arr)):
    if arr[i]+arr[j]==sum:
    count+=1
    print(count)

    ReplyDelete
  32. #Find duplicates in an array
    arr=np.array([1,1,2,2,5,9,6,6,3,4,7,8,5,-1,-1,-9876,-9876])
    for i in range(0,len(arr)):
    for j in range(i+1,len(arr)):
    if arr[i]==arr[j]:
    print(arr[i])

    ReplyDelete
  33. #find max element in numpy array
    import numpy as np
    m=0
    ar=np.array([5,6,4,81,111,7])
    for i in ar:
    if m<i:
    m=i
    print("max element is:-",m)

    ReplyDelete
  34. #WAP to sort the elements of the NumPy array?
    import numpy as np
    ar=np.array([5,9,6,2,8,95,62,32,45])
    for i in range(0,len(ar)):
    for j in range(i+1,len(ar)):
    if ar[i]>ar[j]:
    ar[i],ar[j]=ar[j],ar[i]
    print(ar)

    ReplyDelete
  35. #WAP to split one array into two different subarrays?
    import numpy as np
    ar=np.array([1,9,6,5,8,4,6,3,2,8,5,7,4])
    a=ar[0:int(len(ar)/2)]
    b=ar[int(len(ar)/2):len(ar)]
    print(a)
    print(b)

    ReplyDelete
  36. #WAP to merge two NumPy arrays into one array
    import numpy as np
    ar1=np.array([1,7,3,9,3,5,6,7])
    ar2=np.array([4,65,4,32,5,6,7])
    ar3=np.concatenate((ar1,ar2))
    print(ar3)

    ReplyDelete
  37. #WAP to display prime elements in Numpy array
    import numpy as np
    ar=np.array([4,9,6,3,7,8,5,1,2])
    for i in range(0,len(ar)):
    if ar[i]>=2:
    for j in range(2,ar[i]):
    if (ar[i]%j)==0:
    break
    else:
    print(ar[i])

    ReplyDelete

Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post