Manual
Manual
Algorithm:
result=[ [0,0,0],[0,0,0],[0,0,0] ]
#list comprehension
result= [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]
for k in result:
print(k)
return 0
print("Result: ")
Multiply(A,B)
OUTPUT:
[32, 71]
[37, 52]
[23, 24]
Result:
AIM:
Write a NumPy program to find the number of elements of an array, length of one array element
in bytes and total bytes consumed by the elements.
ALGORITHM:
1. Start at index 1.
2. Test for a value at the current index.
3. If a value is found, double the index.
4. If no value is found subtract the second-to-last index used.
5. Continue with step 4, halving the subtracted value on each iteration until the index is small enough for a
value to be found again.
6. Increment the index by one untill no value is found.
7. The second-last index will be the size.
PROGRAM:
import numpy as np
x = np.array([1,2,3], dtype=np.float64)
Pictorial Presentation:
OUTPUT:
Result:
Number of elements of an array, length of one array element in bytes and total bytes consumed by the
elements was found by using Numpy
EX.NO:4 Frequency of each word in a string
Aim:
To write a python program to find frequency of each word in a string python frequency distribution.
Algorithm:
Program:
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
# printing result
print("Count of all characters in GeeksforGeeks is :\n "
+ str(all_freq))
Output :
Count of all characters in GeeksforGeeks is :
{'r': 1, 'e': 4, 'k': 2, 'G': 2, 's': 2, 'f': 1, 'o': 1}
Result:
Aim:
To Write a Python program to arrange the elements in sorted order using Bubble,
Algorithm:
Step 1) Get the total number of elements. Get the total number of items in the given list
Step 2) Determine the number of outer passes (n – 1) to be done. Its length is list minus one
Step 3) Perform inner passes (n – 1) times for outer pass 1. Get the first element value and
compare it with the second value. If the second value is less than the first value, then swap
the positions.
Step 4) Repeat step 3 passes until you reach the outer pass (n – 1). Get the next element in
the list then repeat the process that was performed in step 3 until all the values have been
Step 5) Return the result when all passes have been done. Return the results of the sorted list.
STEP 6).All types of sorting will be solve the same as per the particular concepts.
Program:
L=[]
a=int(input(""))
L.append(a)
#bubble sort
if (L[j]>L[j+1]):
temp=L[j]
L[j]=L[j+1]
L[j+1]=temp
if (L[i]<L[j]):
temp=L[i]
L[i]=L[j]
L[j]=temp
# selection sort
if (L[i]>L[j]):
temp=L[i]
L[i]=L[j]
L[j]=temp
OUTPUT:
56
86
85
366
14
bubble sorted list is: [4, 14, 56, 85, 86, 366]
insertion sorted list is: [4, 14, 56, 85, 86, 366]
Arranged the elements in sorted order using Bubble, Selection and Insertion sorting techniques by using
Python program.
Ex.No:6 Create and Display a data frame
AIM:
To Write a Pandas program to create and display a Data Frame from a specified dictionary
ALGORITHM:
1.A Data Frame is a two-dimension collection of data. It is a data structure where data is
2. Datasets are arranged in rows and columns; we can store multiple datasets in the data
frame.
3.We can perform various arithmetic operations, such as adding column/row selection and
4.We can import the DataFrames from the external storage; these storages can be referred to
as the SQL Database, CSV file, and an Excel file. We can also use the lists, dictionary, and
6.The dictionary can be passed to create a dataframe. We can use the Dicts of series where
the subsequent index is the union of all the series of passed index value.
PROGRAM:
import pandas as pd
import numpy as np
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df)
OUTPUT:
b 3 Dima no 9.0
d 3 James no NaN
e 2 Emily no 9.0
h 1 Laura no NaN
i 2 Kevin no 8.0
RESULT:
Thus the Data Frame from a specified dictionary and the data which has the index labels was displayed and
created successfully.
Ex.no:7 MATPLOTLIB
Aim:
To write a python program to create and display a line charts and plot two or more lines using matplotlib.
Algorithm:
Step 1:Import necessary libraries from matplotlib for visualization numpy for data creation and manipulation
etc.
Step 2: Deleting the data values that has to be visualized (Define X and Y or array or data frame)
Step 3:Pot the data and adding the features you want in the plot.
Program:
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
fig = plt.figure(figsize = (5, 4))
Output:
Result:
Created and display a line charts and plot two or more lines using matplotlib.
Algorithm:
2. Subtract the mean from each value in the data set. ...
3. Now square each of the values so that you now have all positive values. ...
4. Finally, divide the sum of the squares by the total number of values in the set to find the variance.
Program:
def variance(val):
numb = len(val)
m = sum(val) / numb
# Square deviations
# Variance
return variance
print(variance([6, 6, 3, 9, 4, 3, 6, 9, 7, 8]))
Output:
4.49
Result:
Using python code from total number of values in the set to find the variance
Algorithm:
1.pd.concat() can be used for a simple concatenation of Series or DataFrame objects, just
as np.concatenate() can be used for simple concatenations of arrays.
2. By default, the concatenation takes place row-wise within the DataFrame (i.e., axis=0).
Like np.concatenate, pd.concat allows specification of an axis along which concatenation will take place.
3. Pandas provide such facilities for easily combining Series or DataFrame with various kinds of set logic
for the indexes and relational algebra functionality in the case of join / merge-type operations.
Program:
import pandas as pd
# First DataFrame
# Second DataFrame
result = pd.concat(frames)
display(result)
output:
Result:
Algorithm:
1.Attributes are the properties of a DataFrame that can be used to fetch data or any information related to a
particular dataframe.
DataFrame_name.attribute
3. index
There are two types of index in a DataFrame one is the row index and the other is the column index. The
index attribute is used to display the row labels of a data frame object. The row labels can be of 0,1,2,3,…
form and can be of names.
Syntax: dataframe_name.index
4. As we have not mentioned any index labels in this program, it will automatically take the index from 0
to n numbers where n is the number of rows and then printed on the output screen.
Program:
import pandas as pd
# creating a 2D dictionary
"Priya", "Rahul"],
# creating a DataFrame
df = pd.DataFrame(dict)
# output screen
display(df)
# this DataFrame
print(df.index)#attribute index
print(df.shape)#attribute shape
print(“The size of the dataset is:”)
print(df.size)#attribute size
print(df.ndim)#attribute ndim
OUTPUT:
(4,3)
12
Result:
ALGORITHM:
1.Extracting text from images is a very popular task in the operations units of the business (extracting
information from invoices and receipts) as well as in other areas.
2. OCR (Optical Character Recognition) is an electronic computer-based approach to convert images of text
into machine-encoded text, which can then be extracted and used in text format.
3. Tesseract is an open source OCR (optical character recognition) engine which allows to extract text from images.
4.In order to use it in Python, we will also need the pytesseract library which is a wrapper for Tesseract
engine.
5.Since we are working with images, we will also need the pillow library which adds image processing
capabilities to Python.
6.First, search for the Tesseract installer for your operating system. For Windows, you can find the latest
version of Tesseract installer here. Simply download the .exe file and install on your computer.
7.If you don’t have the Python libraries installed, please open “Command Prompt” (on Windows) and install
them using the following code:
Program:
Print(“VISUAL CHARACTER-IMAGE”)
image_path = r"csv\sample_text.png"
pytesseract.tesseract_cmd = path_to_tesseract
text = pytesseract.image_to_string(img)
print(text[:-1])
Output:
Visual character-IMAGE
An Autonomous Institution
Result:
An Image Data was extracted from the visual character was successfully
Algorithm:
1.Consider a model that predicts 150 examples for the positive class,
Program:
import pandas as pd
import numpy as np
X = loan.drop(['default'],axis=1)
Y = loan['default'].astype(str)
def err_metric(CM):
TN = CM.iloc[0,0]
FN = CM.iloc[1,0]
TP = CM.iloc[1,1]
FP = CM.iloc[0,1]
precision =(TP)/(TP+FP)
accuracy_model =(TP+TN)/(TP+TN+FP+FN)
recall_score =(TP)/(TP+FN)
False_positive_rate =(FP)/(FP+TN)
False_negative_rate =(FN)/(FN+TP)
#Decision Trees
target = decision.predict(X_test)
targetclass_prob = decision.predict_proba(X_test)[:, 1]
confusion_matrix = pd.crosstab(Y_test,target)
err_metric(confusion_matrix)
Output:
Result:
Thus the python program for precision and decision of searching on a dataset was calculated successfully.
Aim:
To Create a Pivot Table in Python using Pandas.
Algorithm:
1. In the pivot_table function, specify the DataFrame you are summarizing, along with the
names for the indexes, columns and values.
2. Specify the type of calculation you want to use, such as the mean.
3. multiple indexes and column-level grouping to create a more powerful summary of the
data.
• Values: These are the numerical values you are looking to summarize.
Program:
import pandas as pd
data = {'person': ['A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'],'sales': [1000,
300, 400, 500, 800, 1000, 500, 700, 50, 60, 1000, 900, 750, 200, 300, 1000, 900, 250, 750, 50], 'quarter': [1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4],'country': ['US', 'Japan', 'Brazil', 'UK', 'US', 'Brazil', 'Japan',
'Brazil', 'US', 'US', 'US', 'Japan', 'Brazil', 'UK', 'Brazil', 'Japan', 'Japan', 'Brazil', 'UK', 'US']
df = pd.DataFrame(data)
print(pivot)
Output:
sales
mean median min
country
Brazil 566.666667 550.0 250.0
Japan 720.000000 900.0 300.0
UK 483.333333 500.0 200.0
US 493.333333 430.0 50.0
Result: