You are on page 1of 42

PYTHON SKILL BASED MINI PROJECT

Real time currency converter ( Paisa Converter)

Bachelor of Technology
By

HARSH SHUKLA

0901IO211023
Under the Supervision of

DR. BHAGAT SINGH RAGHUWANSHI

DR.VIKRAM RAJPOOT

PYTHON PROGRAMMING LAB(230406)


Department of Informa on
Technology

DEPARTMENT OF INFORMATION TECHNOLOGY


MADHAV INSTITUTE OF TECHNOLOGY &
SCIENCEGWALIOR, INDIA APRIL 2023

1|Page
CERTIFICATE

This is to certify that the work contained in this project entitled “Real Time Currency

Converter (Paisa Converter)”, has been carried out by students mentioned below from the

Department of Information Technology. This project was done on partial fulfillment of B.

Tech. Mini Skill Based Project of Laboratory course “Python Programming Lab

(230406).” It has been found to be satisfactory and hereby approved for submission.

Name of Student Roll No. Sign of Student

HARSH SHUKLA 0901IO211023

(Dr. Bhagat Singh Raghuwanshi)


Department of Information Technology,
Madhav Institute of Technology &
Science,
Gwalior-474005, M.P., India

Sign of Teacher

(Dr. Vikram Rajpoot)


Assistant Professor
Department of Information Technology,
Madhav Institute of Technology &
Science,
Gwalior-474005, M.P., India

Sign of Teacher

2|Page
ACKNOWLEDGEMENT

Merely a page would definitely fall short if I have to acknowledge all those behind this

accomplishment. However, I am bound by words to acknowledge them. Looking back while

writing this project, I recall and acknowledge the inspiration, cooperation and

encouragement received from numerous known and unknown people.

First of all, I acknowledge the blessings of Almighty and thank the divine power for

gracing me with the peace of mind and endurance to carry out this work diligently and

honestly.

I would like to express my deepest appreciation and heartfelt gratitude to Dr. Singh

Raghuwanshi and Dr. Vikram Rajpoot for their continuous support, guidance, motivation

and insightful comments. They substantially enriched this research work with their sound

knowledge. They were always available for day-to-day discussion, gave me the freedom to

work without feeling pressure and was very flexible towards problem solving approach.

Their commitment towards high quality research work made this work rewarding. I feel

privileged to work under their esteemed supervision.

I sincerely acknowledge my Head of the Department Prof. Akhilesh Tiwari, who made

the environment of the department supportive for project work.

My earnest gratitude goes out to my parents and my sister who sacrificed a lot for me,

always motivated me and stood as a pillar of strength for me with unending faith and

empathy during all these years.

Finally, I would like to thank all my friends, relatives and colleagues without whom it
would have been difficult to enjoy this research work.

Thank you and may God bless you all!


Harsh Shukla (0901IO211023)

Teachers Sign Student Sign

3|Page
Table of Content

S.no Title Page no. Sign

1. Introduction to Project

2. Algorithm of Project

3. Source Code

4. Working

5. Conclusion

6. Micro Project

7. Macro Project

4|Page
Introduction to project
Real-time currency converter is a project that helps in converting one currency to another
currency. This project uses live currency exchange rates to convert currencies. The project is
built using Python programming language and requires knowledge of different Python
libraries such as Tkinter and modules such as currency_converter.
The project aims to provide a user-friendly interface that allows the user to enter the amount
they want to convert, the currency they want to convert from and the currency they want to
convert to. The project then fetches the live currency exchange rates using class
CurrencyConverter and performs the conversion. The result is then displayed to the user.

Library Used:
(i) Tkinter
(ii) CurrencyConverter

 Tkinter is a standard Python library used for creating graphical user interfaces (GUIs).
It provides a set of tools for creating windows, buttons, menus, text boxes, and other
GUI elements. Tkinter is the standard GUI library for Python and is included with
most Python installations.

 Tkinter is built on top of the Tcl/Tk GUI toolkit. It provides a simple and intuitive
way to create GUIs for desktop applications. Tkinter allows developers to create
interactive applications with ease, providing a range of widgets and tools that can be
easily customized.

Some of the key features of Tkinter include:

1. Easy to use: Tkinter is easy to use and does not require advanced programming skills.
2. Cross-platform: Tkinter is available on many platforms, including Windows,
Mac OS, and Linux.
3. Customizable: Tkinter widgets can be customized to suit the specific needs of an
application.
4. Wide range of widgets: Tkinter provides a wide range of widgets including buttons,
labels, menus, and text boxes.
5. Integration: Tkinter can be easily integrated with other Python libraries and tools.
Overall, Tkinter is a powerful and versatile library for creating GUIs in Python. It is widely
used for building desktop applications, scientific and engineering applications, and more.
 CurrencyConverter is a Python library used for currency conversion. It provides a
simple and easy-to-use interface for converting one currency to another. The library is
built using Python and is available for use on a variety of platforms.
Some of the key features of CurrencyConverter include:
1. Easy to use: CurrencyConverter is easy to use and does not require advanced
programming skills.

2. Cross-platform: CurrencyConverter is available on many platforms, including


Windows, Mac OS, and Linux.

3. Supports a wide range of currencies: CurrencyConverter supports over 170


currencies, including cryptocurrencies like Bitcoin.

5|Page
4. Real-time currency exchange rates: CurrencyConverter uses real-time currency
exchange rates to provide accurate currency conversion.

5. Customizable: CurrencyConverter can be customized to suit the specific needs of an


application.

6. The library provides a CurrencyConverter class that can be used to perform currency
conversions. The class takes the amount to be converted, the currency to convert
from, and the currency to convert to as arguments. The library then fetches the latest
currency exchange rates from a reliable source and performs the conversion.

7. Overall, CurrencyConverter is a useful library for developers who need to perform


currency conversions in their Python applications. It is widely used for building
financial and e-commerce applications, as well as for data analysis and visualization.

Algorithm Of Project
1. Import the CurrencyConverter module from currency_converter and tkinter module as
tk.
2. Create an instance of the CurrencyConverter class and store it in a variable 'a'.
3. Create a tkinter window using the Tk() method and set its geometry.
4. Define a function named 'clicked()' which will be executed when the button is clicked.
5. Inside the 'clicked()' function, extract the user input from the three Entry widgets as
amount, cur1 and cur2 respectively.
6. Convert the entered amount in the given currency to the required currency using the
convert() method of the CurrencyConverter class.
7. Create two Labels 'l5' and 'l6' containing the converted currency value and the
developer name and place them on the tkinter window.
8. Create Label widgets to display text 'Paisa Converter', 'Enter Amount here:', 'Enter
Currency:', 'Enter Req Currency:', and place them on the window at appropriate
positions.
9. Create Entry widgets e1, e2 and e3 for the user to enter amount, current currency and
required currency respectively, and place them on the window.
10. Create a Button widget 'b1' with text 'click' which will execute the 'clicked()' function
on click, and place it on the window.
11. Place the Entry widgets on the window at appropriate positions using the place()
method.
12. Start the mainloop of the tkinter window using the mainloop() method.

6|Page
Source Code
from currency_converter import CurrencyConverter
import tkinter as tk

a = CurrencyConverter()

window = tk.Tk()
window.geometry("900x400")

def clicked():
amount = int(e1.get())
cur1 = e2.get()
cur2 = e3.get()
data = a.convert(amount , cur1 , cur2)
l5 = tk.Label(window, text="Curreny Conversion from "+ cur1+" to "+cur2+" : "+ str(data),
font="Times 18 bold").place(x=90 , y = 290)
l6 = tk.Label(window, text="BY HARSH SHUKLA (0901IO211023)", font="Times 20
bold").place(x=90, y=340)
l1 = tk.Label(window, text="Paisa Converter", font="Times 20 bold").place(x=180, y=30)

l2 = tk.Label(window, text="Enter Amount here:", font="Times 18 bold").place(x=50, y=90)


e1 = tk.Entry(window)

l3 = tk.Label(window, text="Enter Currency:", font="Times 18 bold").place(x=50, y=130)


e2 = tk.Entry(window)

l4 = tk.Label(window, text="Enter Req Currency:", font="Times 18 bold").place(x=50, y=180)


e3 = tk.Entry(window)

b1 = tk.Button(window, text="click", command=clicked).place(x=350, y=230)


e1.place(x=300, y=90)
e2.place(x=300, y=130)
e3.place(x=300, y=180)
window.mainloop()

7|Page
Working Of Source Code
1. from currency_converter import CurrencyConverter - imports the CurrencyConverter
class from the currency_converter module.

2. import tkinter as tk - imports the tkinter module and gives it the alias tk for easier use.

3. a = CurrencyConverter() - creates an instance of the CurrencyConverter class and


assigns it to the variable a.

4. window = tk.Tk() - creates a new Tk object, which is the main window of the
application.

5. window.geometry("900x400") - sets the size of the window to 900 pixels wide and
400 pixels high.

6. def clicked(): - defines a function named clicked that will be called when the button is
clicked.

7. amount = int(e1.get()) - retrieves the value from the e1 Entry widget and converts it to
an integer, assigning it to the variable amount.

8. cur1 = e2.get() - retrieves the value from the e2 Entry widget and assigns it to the
variable cur1.

9. cur2 = e3.get() - retrieves the value from the e3 Entry widget and assigns it to the
variable cur2.

10. data = a.convert(amount , cur1 , cur2) - calls the convert method of the
CurrencyConverter object with the given arguments and assigns the result to data.

11. l5 = tk.Label(window, text="Curreny Conversion from "+ cur1+" to "+cur2+" : "+


str(data), font="Times 18 bold").place(x=90 , y = 290) - creates a Label widget and
assigns it to l5, which displays the converted currency data along with a message.

12. l6 = tk.Label(window, text="BY HARSH SHUKLA (0901IO211023)", font="Times


20 bold").place(x=90, y=340) - creates another Label widget and assigns it to l6,
which displays the name of the developer.

13. l1 = tk.Label(window, text="Paisa Converter", font="Times 20 bold").place(x=180,


y=30) - creates a Label widget and assigns it to l1, which displays the title of the
application.

14. l2 = tk.Label(window, text="Enter Amount here:", font="Times 18


bold").place(x=50, y=90) - creates a Label widget and assigns it to l2, which displays
a message prompting the user to enter an amount.

8|Page
15. e1 = tk.Entry(window) - creates an Entry widget and assigns it to e1, which is used
for the user to enter the amount to be converted.

16. l3 = tk.Label(window, text="Enter Currency:", font="Times 18 bold").place(x=50,


y=130) - creates a Label widget and assigns it to l3, which displays a message
prompting the user to enter the currency to convert from.

17. e2 = tk.Entry(window) - creates an Entry widget and assigns it to e2, which is used
for the user to enter the currency to convert from.

18. l4 = tk.Label(window, text="Enter Req Currency:", font="Times 18


bold").place(x=50, y=180) - creates a Label widget and assigns it to l4, which
displays a message prompting the user to enter the currency to convert to.

19. e3 = tk.Entry(window) - creates an Entry widget and assigns it to e3, which is used
for the user to enter the currency to convert to.

20. b1 = tk.Button(window, text="click", command=clicked).place(x=350, y=230) -


creates a Button widget and assigns it to b1, which is used to trigger the conversion of
currency when clicked. The command attribute of the button is set to the function
clicked, which will be called when the button is clicked.

21. e1.place(x=300, y=90) - sets the position of the e1 Entry widget to (300, 90) on the
main window.

22. e2.place(x=300, y=130) - sets the position of the e2 Entry widget to (300, 130) on the
main window.

23. e3.place(x=300, y=180) - sets the position of the e3 Entry widget to (300, 180) on the
main window.

24. window.mainloop() - starts the main event loop of the application, which listens for
events such as user inputs, button clicks, and updates the display. The program will
remain in this loop until the user closes the window or the program is terminated.

Conclusion
The library provides a CurrencyConverter class that can be used to perform currency
conversions. The class takes the amount to be converted, the currency to convert from,
and the currency to convert to as arguments. The library then fetches the latest
currency exchange rates from a reliable source and performs the conversion.

Overall, CurrencyConverter is a useful library for developers who need to perform


currency conversions in their Python applications. It is widely used for building
financial and e-commerce applications, as well as for data analysis and visualization.

9|Page
LIST OF MICRO PROGRAMS
MICRO PROGRAM 1ST
#1-> Demonstrate about fundamental Data types in Python Programming. (i.e., int, float, complex, bool and
string types)
#BY HARSH SHUKLA (0901IO211023)

a=1
print(type(a))
a = 1.3
print(type(a))
a = 1+2j
print(type(a))
a = True
print(type(a))
a = 'a'
print(type(a))
a = "Harsh";
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 1ST MICRO PROGRAM :

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'str'>
<class 'str'>

BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 2ND


#2 -> Demonstrate the working of following functions in Python.
# i) id( ) ii) type( ) iii) range( )
#BY HARSH SHUKLA (0901IO211023)

#demonstarting id()
var = 60
print(id(var)) #id function mainly discribes the address(unique id) of varibale

#demonstrarting type()
var1 = 'Harsh'
print(type(var1))
#type() describes the data type of the variable
var2 = 1+2j
print(type(var2))

#demonstarting range()
lst = []

10 | P a g e
lst = list(range(0,10)) #it give the number specifed from start , end - 1
print(lst)
print("BY HARSH SHUKLA")
print("0901IO211023")
OUTPUT OF 2ND MICRO PROGRAM :

2241509066832
<class 'str'>
<class 'complex'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 3RD


#3rd->Write a Python program to demonstrate various base conversion functions.
#BY HARSH SHUKLA(0901IO211023)
def decimal_to_binary(decimal_num):
"""Converts decimal number to binary."""
return bin(decimal_num)

def binary_to_decimal(binary_num):
"""Converts binary number to decimal."""
return int(binary_num, 2)

def decimal_to_hex(decimal_num):
"""Converts decimal number to hexadecimal."""
return hex(decimal_num)

def hex_to_decimal(hex_num):
"""Converts hexadecimal number to decimal."""
return int(hex_num, 16)

# Examples
print(decimal_to_binary(9))
print(binary_to_decimal('0b1000'))
print(decimal_to_hex(189))
print(hex_to_decimal('0xfe'))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 3RD MICRO PROGRAM :

0b1001
8
0xbd
254
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 4TH

11 | P a g e
#Write a Python program to demonstrate various type conversion functions.
#BY HARSH SHUKLA (0901IO211023)

# Converting strings to integers


num1 = int('10')
num2 = int('1010', 2) # Convert binary string to integer

# Converting strings to floats


float1 = float('3.14')
float2 = float('2.71828e-3')

# Converting integers to strings


str1 = str(42)
str2 = str(0b1010) # Convert binary integer to string

# Converting floats to strings


str3 = str(3.14159)
str4 = str(2.71828e-3)

# Converting integers to floats


float3 = float(42)

# Converting floats to integers


num3 = int(3.14)

# Examples
print(num1)
print(num2)
print(float1)
print(float2)
print(str1)
print(str2)
print(str3)
print(str4)
print(float3)
print(num3)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 4TH MICRO PROGRAM :

10
10
3.14
0.00271828
42
10
3.14159
0.00271828
42.0
3
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 5TH

12 | P a g e
ARITHMATIC OPERATORS
'''+ , - , * , / , % , ** , //'''
a = 10
b = 20
print(a+b)
print(a-b)
print(a*b)
print(a/b)#it give a/b but in float form
print(a%b)#it give reamainder
print(a**2)# it give the power means a->number 2-> kitna divide karna hai
print(a//b)# it give value a/b in integer form
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.0 :

30
-10
200
0.5
10
100
0
BY HARSH SHUKLA
0901IO211023

INCREMENT/DECREMENT OPERATORS
''' = , += , -='''
#here ++ , -- (increment or decrement operator doesn't work)
a = 20
print(a)
a+=5 #a=a+5
print(a)
a-=5 #a = a - 5
print(a)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.1 :

20
25
20
BY HARSH SHUKLA
0901IO211023

BITWISE OPERATORS
'''& , | , ^'''
a = 10

13 | P a g e
b=8
print(a&b) #with bin() we get number in numeric form
print(bin(a)) # bin() is a function to get the binary form of a number in 5 bit form
print(bin(b))
print(bin(a&b)) # ans would be in binary formate becuase we write bin() to convert ans

print(a|b) #with bin() we get number in numeric form


print(bin(a)) # bin() is a function to get the binary form of a number in 5 bit form
print(bin(b))
print(bin(a|b)) # ans would be in binary formate becuase we write bin() to convert ans

print(a^b) #with bin() we get number in numeric form


print(bin(a)) # bin() is a function to get the binary form of a number in 5 bit form
print(bin(b))
print(bin(a^b)) # ans would be in binary formate becuase we write bin() to convert ans
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.2 :


8
0b1010
0b1000
0b1000
10
0b1010
0b1000
0b1010
2
0b1010
0b1000
0b10
BY HARSH SHUKLA
0901IO211023

COMPARISON OPERATORS

'''> , < , >= , <= , == , !='''


x = 10
y = 20
print(x>y)
print(x<y)
print(x>=y)
print(x<=y)
print(x!=y)
print(x==y)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.3 :


False
True
False
True

14 | P a g e
True
False

BY HARSH SHUKLA
0901IO211023

IDENTITY OPERATORS

''' is , is not '''


#important concepts about identity and equality operator
'''identity operator works on the address space of a variable but equality operator works on the value of the
variable '''
a = 10
b = 10
print( a is b) #address space of a and b are same because value is same therefore ans will be true
print(a==b) #yes true becasue value of both variables are same

#now for string


a = "hello"
b = "hello"
print(a is b) #true
print(a == b) #true
#now using whitespaces
a = "Hello World"
b = "Hello World"
print(a is b)
print(a == b)
#using multiple assign
a = b = "hello"
print(a is not b)
print(a!=b)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.4 :

True
True
True
True
True
True
False
False

BY HARSH SHUKLA
0901IO211023

LOGICAL OPERATORS

''' and , or , not'''


a = 10
b = 20
print(a>b or a!=b or a==b) #if one condition from n conditions are true then or returns true and skip other
statements

15 | P a g e
print(a>b and a==b) #and check all n conditions are true or not if all true then it returns true otherwise false
print ( not a!=b) #reverse the condition true becomes false and false becomes true
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.5 :


True
False
False
BY HARSH SHUKLA
0901IO211023

MEMBERSHIP OPERATORS

''' in and not in'''


'''mainly used in pyhton data types like , string , list , tuples , dictonaries '''
string1 = "Hello"
print('h' in string1)
string1 = "Shukla"
print('h' in string1)
string1 = "JI"
print('j' not in string1)
l = [10,20,30,40] #this is list of numbers
print( 50 in l)
print("BY HARSH SHUKLA ")
print("0901IO211023")

OUTPUT OF 5TH MICRO PROGRAM -> 1.5 :


False
True
True
False
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 6TH

'''Write Python programs to demonstrate the following:


i) input( )
ii) print( )
iii) ‘sep’ attribute
iv) ‘end’ attribute
v) replacement Operator ({ })'''
#BY HARSH SHUKLA
#0901IO211023

#input()
Name = input("Enter your Name : ")

#print()
print("Name Entered : ",Name)

#'sep' attribute

16 | P a g e
print("This is very costly",sep='!')

#'end' attribute

print("Hello Harsh how are you",end=',')

#replacement operator
name = "Harsh"
age = 18

print("My name is {0} and I am {1} years old.".format(name, age))

print("BY HARSH SHUKLA")


print("0901IO211023")

OUTPUT OF 6TH MICRO PROGRAM :

Enter your Name : HARSH SHUKLA


Name Entered : HARSH SHUKLA
This is very costly
Hello Harsh how are you,My name is Harsh and I am 18 years old.
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 7TH


'''Demonstrate the following Conditional statements in Python with
suitable examples.
i) if statement
ii) if else statement
iii) if – elif – else statement '''
#BY HARSH SHUKLA (0901IO211023)

#if construct
age = 20

if age >= 18:


print("You are eligible to vote.")

#if else construct


age = 15

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")

#if elif else construct

marks = 75

if marks >= 90:


grade = 'A'
elif marks >= 80:

17 | P a g e
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'

print("Your grade is", grade)

print("BY HARSH SHUKLA")


print("0901IO211023")

OUTPUT OF 7TH MICRO PROGRAM :

You are eligible to vote.


You are not eligible to vote yet.
Your grade is C
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 8TH

'''Demonstrate the following Iterative statements in Python with


suitable examples.
i) while loop ii) for looP'''
#BY HARSH SHUKLA (0901IO211023)

#while loop
count = 0

while count < 5:


print(count)
count += 1

#for loop
fruits = ["apple", "banana", "cherry", "orange"]

for fruit in fruits:


print(fruit)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 8TH MICRO PROGRAM :

0
1
2
3
4
apple
banana
cherry

18 | P a g e
orange
BY HARSH SHUKLA
0901IO211023

MICRO PROGRAM 9TH


'''Demonstrate the following control transfer statements in Python with
suitable examples.
i) break
ii) continue
iii) pass '''
#BY HARSH SHUKLA(0901IO211023)

#break
numbers = [1, 2, 3, 4, 5]

for num in numbers:


if num == 3:
break
print(num)

print("Loop exited.")

#continue
numbers = [1, 2, 3, 4, 5]

for num in numbers:


if num == 3:
continue
print(num)

print("Loop exited.")

#pass
def hello():
pass
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 9TH MICRO PROGRAM :

1
2
Loop exited.
1
2
4
5
Loop exited.
BY HARSH SHUKLA
0901IO211023

19 | P a g e
LIST OF MACRO PROGRAMS

MACRO PROGRAM 1ST

'''Write a Python program to demonstrate various ways of


accessing the string.
i) By using Indexing (Both Positive and Negative)
ii) By using Slice Operator '''
#BY HARSH SHUKLA (0901IO211023)

#String Indexing ( +ve and -ve)

my_string = "Harsh Shukla!"

# Accessing the first character of the string using positive indexing


print("First character using positive indexing:", my_string[0])

# Accessing the last character of the string using positive indexing


print("Last character using positive indexing:", my_string[-1])

# Accessing the second character of the string using negative indexing


print("Second character using negative indexing:", my_string[-12])

# Accessing the second last character of the string using negative indexing
print("Second last character using negative indexing:", my_string[-2])

# Accessing a substring using positiv"e indexing


print("Substring using positive indexing:", my_string[6:11])

# Accessing a substring using negative indexing


print("Substring using negative indexing:", my_string[-6:-1])

#String Slicing
st = "Harsh Shukla"
print(st[:3] + st[3:])
print(st[:3],st[3:])
print(st[::-1])
print(st[:-5] + st[-5:])
print(st[11:18])
print(st[12:21])
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 1ST MACRO PROGRAM :

First character using posi ve indexing: H


Last character using posi ve indexing: !
Second character using nega ve indexing: a
Second last character using nega ve indexing: a
Substring using posi ve indexing: Shukl
Substring using nega ve indexing: hukla
Harsh Shukla
Har sh Shukla

20 | P a g e
alkuhS hsraH
Harsh Shukla
a

BY HARSH SHUKLA
0901IO211023

MACRO PROGRAM 2ND

'''Demonstrate the following functions/methods which operates on


strings in Python with suitable examples:
i) len( ) ii) strip( ) iii) rstrip( ) iv) lstrip( ) v) find( ) vi) rfind( ) vii)
index( ) viii) rindex() ix) count( ) x) replace( ) xi) split( ) xii) join(
) xiii) upper( ) xiv) lower( ) xv) swapcase( ) xvi) title( ) xvii)
capitalize( ) xviii) startswith() xix) endswith() '''
#BY HARSH SHUKLA (0901IO211023)
# Define a sample string
my_string = " Hello World! "

# len()
print("Length of the string:", len(my_string))

# strip()
print("String after stripping whitespace:", my_string.strip())

# rstrip()
print("String after stripping whitespace from the right:", my_string.rstrip())

# lstrip()
print("String after stripping whitespace from the left:", my_string.lstrip())

# find()
print("Index of 'World' in the string:", my_string.find("World"))

# rfind()
print("Index of last 'o' in the string:", my_string.rfind("o"))

# index()
print("Index of 'World' in the string:", my_string.index("World"))

# rindex()
print("Index of last 'o' in the string:", my_string.rindex("o"))

# count()
print("Number of 'l' characters in the string:", my_string.count("l"))

# replace()
print("String after replacing 'World' with 'Universe':", my_string.replace("World", "Universe"))

# split()
print("List of words in the string:", my_string.split())

# join()

21 | P a g e
list_of_words = ["Hello", "World"]
print("String after joining the list of words:", " ".join(list_of_words))

# upper()
print("Uppercase version of the string:", my_string.upper())

# lower()
print("Lowercase version of the string:", my_string.lower())

# swapcase()
print("String with swapped case:", my_string.swapcase())

# title()
print("Titlecased version of the string:", my_string.title())

# capitalize()
print("Capitalized version of the string:", my_string.capitalize())

# startswith()
print("Does the string start with 'Hello'?", my_string.startswith("Hello"))

# endswith()
print("Does the string end with 'World!'?", my_string.endswith("World!"))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 2ND MACRO PROGRAM :

Length of the string: 17


String a er stripping whitespace: Hello World!
String a er stripping whitespace from the right: Hello World!
String a er stripping whitespace from the le : Hello World!
Index of 'World' in the string: 9
Index of last 'o' in the string: 10
Index of 'World' in the string: 9
Index of last 'o' in the string: 10
Number of 'l' characters in the string: 3
String a er replacing 'World' with 'Universe': Hello Universe!
List of words in the string: ['Hello', 'World!']
String a er joining the list of words: Hello World
Uppercase version of the string: HELLO WORLD!
Lowercase version of the string: hello world!
String with swapped case: hELLO wORLD!
Titlecased version of the string: Hello World!
Capitalized version of the string: hello world!
Does the string start with 'Hello'? False
Does the string end with 'World!'? False

BY HARSH SHUKLA
0901IO211023

22 | P a g e
MACRO PROGRAM 3RD

'''Examples of map() , reduce() , and filter() and using map() , reduce() and filter() with lambda function'''
#BY HARSH SHUKLA (0901IO211023)
#map()
l = [1,2,3,4,5] #square of each element of list
def sqr(l):
l1 = []
for i in l:
l1.append(i**2)
return l1
print(sqr(l))

#map(fun(kuch bhee ho skta hai) , iterable(string , list , dic))


def sqr1(x):
return x**2
print(list(map(sqr1 , l)))

#we can also use lambda function in map()


print(list(map(lambda x : x**2 , l)))

#another example of map() with lambda function


print(list(map(lambda x : x , l)))

#adding of two lists


l11 = [2,4,5,7,8]
l22 = [4,7,9,1,3]
print(list(map(lambda x,y : x+y , l11, l22)))

#covert whole string into upper cased list


s = "harsh shukla"
print(list(map(lambda x : x.upper(),s)))

#reduce()
from functools import reduce
ll = [1,2,3,4,5,6]
print(reduce(lambda x,y : x + y , ll))

#more example of reduce()


print(reduce(lambda x,y : x*y , ll))

#to find maximum using reduce function


print(reduce(lambda x,y : x if x > y else y , ll))

#filter()
#to find even number from list
print(list(filter(lambda x : x%2==0 , ll)) )#even number

#to find negative number


print(list(filter(lambda x : x<0 , ll)))

#more example of filter function


l21 = ["harsh","shukla", "is ","my","name"]
print(list(filter(lambda x : len(x)<4 , l21)))
print("BY HARSH SHUKLA")
print("0901IO211023")

23 | P a g e
OUTPUT OF 3RD MACRO PROGRAM :

[1, 4, 9, 16, 25]


[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
[1, 2, 3, 4, 5]
[6, 11, 14, 8, 11]
['H', 'A', 'R', 'S', 'H', ' ', 'S', 'H', 'U', 'K', 'L', 'A']
21
720
6
[2, 4, 6]
[]
['is ', 'my']
BY HARSH SHUKLA
0901IO211023

MACRO PROGRAM 4TH

Numpy Array ( Pandas Library )

#introduction program of NumpyArray


#we are creating a 1-D Numpy Array and checking its type
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
Array_1d = np.array([1,2,3,4,5])
print(Array_1d)
print(type(Array_1d))
#to check our array is 1D,2D or 3D so for this we use ndim parameter
print(Array_1d.ndim)
#now we are creating 2-D Numpy Array is the list of list
Array_2d = np.array([[1,2,3],[4,5,6]])
print(Array_2d)
print(Array_2d.ndim)
#to check the size of Array(kitne no of elements hai hamare array)
print(Array_1d.size)
print(Array_2d.size)
#to check the size of array ( means kitne no of rows hai or kitne no of columns)
#so we use shape function
#ka output tuple ke form me ata hai (row , column)
print(Array_1d.shape) #(1-d Array me sirif rows hoti hai toh column wala parameter khali hoga)
print(Array_2d.shape)
#now if we have to check the data type of array
#so we use dtype function
#output:mutlb array me jo values thi unka type integer hai or unko 32 bits ke form me represent kiya hai
print(Array_1d.dtype)
print(Array_2d.dtype)
print("BY HARSH SHUKLA")
print("0901IO211023")

24 | P a g e
OUTPUT OF 4TH MACRO PROGRAM - > 1.0:

[1 2 3 4 5]
<class 'numpy.ndarray'>
1
[[1 2 3]
[4 5 6]]
2
5
6
(5,)
(2, 3)
int32
int32

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 2

#2nd Program of NumpyArray using more functions


#if we have an identity matrix means an array having all one's like ,
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
Array_1s = np.array([[1,1,1],[1,1,1],[1,1,1]])
print(Array_1s)
#so we can see that we created a 3*3 identity matrix but if we have to create a identity matrix having many
rows and columns
#so for this we have to use ones()-> ones((row,column))-> rows is not compulsory by default single row
Arr_1s = np.ones(5)
#ones ka syntax important hai iske liye humko rows , columns ko tuple ke andar likhna hoga
#so, ones((row,column))
#important note -> ones() me jo matrix banegi uska type float hoga you can check the type of matrix by using
dtype function
print(Arr_1s)
#another example of ones
Arr_1es = np.ones((3,4))
print(Arr_1es)
#agr me chahata hun ki mujhe integer type ka matrix mile toh uske liye mujhe dtype change karna padega
Arr_1ss = np.ones((3,4),dtype = int)
print(Arr_1ss)
#if we have to create a matrix that contains all zeros
#so for this we use zeros() functions , iska sytanx same hai as ones() ka
Arr_0s = np.zeros((5,8), dtype = int)
print(Arr_0s)
#me iska dtype change karke bool me convert kar skta hun
Arr_0es = np.zeros((5,8),dtype = bool)
print(Arr_0es)
#agr me iska str me convert karta hun toh mujhe " "(empty) string milegi

#so agr mujhe numpy me empty matrix create karna hai toh iske liye hum empty() ka istemaal karenge but
empty matrix kuch nhi
#hota hai numpy me agr me empty() ka istemaal karta hun toh voh random value generate kar dega.........
Arr_emp = np.empty((3,5))

25 | P a g e
print(Arr_emp)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.1:

[[1 1 1]
[1 1 1]
[1 1 1]]
[1. 1. 1. 1. 1.]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0]]
[[False False False False False False False False]
[False False False False False False False False]
[False False False False False False False False]
[False False False False False False False False]
[False False False False False False False False]]
[[6.23042070e-307 3.56043053e-307 1.60219306e-306 2.44763557e-307
1.69119330e-306]
[1.78022342e-306 1.05700345e-307 1.24610383e-306 8.45590539e-307
9.34607074e-307]
[6.89805151e-307 1.78020169e-306 1.42410974e-306 3.23796840e-317
2.02369289e-320]]

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 3

#3rd Program of More Numpy Functions


#1st is arange functions
#so if we break arange -> then a + range() so it is like a range function giving starting , ending and step value
#so syntax will be -> arange(start,end,step)
#through arange function we can create a 1-D array
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
arr = np.arange(1,13)
print(arr)
#printing even array upto 12
arr_1 = np.arange(0,13,2)#giving step value as 2
print(arr_1)

#linspace()
#is function me hame ek range deni padti hai or us range me humko kitne numbers chahiye voh bhee batana
hota hai

26 | P a g e
#or jo numbers ate hai voh random ate hai us given range me jo exits karte hai
arr_2 = np.linspace(1,6,5)
#iska mutlb 1 se 6 ke beech me mujhe 5 numbers chahiye voh 5 numbers kuch bhee ho skte hai
print(arr_2)

#reshape()
#important function is respace function hai because iske through hum 1-D array ko 2-D , or 3-D array me
convert kar skte hai
#Conversion of 1-D array to 2-D array
arr_3 = arr.reshape(3,4) #(row,column)
#reshape function me dhiyan ye rakhna hai ki jo product hoga row * column ka voh hamare total no of
elements ke equal hona
#chahiye
print(arr_3)
#Coversion of 1-D array to 3-D array
arr_4 = arr.reshape(3,2,2)#(3-D array kitne parts me divide hoga,row,column)
#sub ka multiplication 12 ke equal hona chahiye
print(arr_4)

#now using both arange() and reshape function we can create a 2-D array
arrd = np.arange(1,13).reshape(2,6)
print(arrd)

#ravel function
#agr hame 2-d ya 3-D array ko 1-D me convert karna hai toh iske liye hum reval function ka istemaal karenge
ar = arrd.ravel()
print(ar)

#flatten function
#flatten function me bhee hum 2-d ya 3-d array ko 1-D me convert kar skte hai but phir ravel or flatten me
difference kiya hai
#so flatten me hum ek paramter bhee de skte hai or mujhe iske bare me jankari nhi dhekna padega
are = arrd.flatten()
print(are)

#transpose function
#transpose function ke through hum rows ko column me interchange kar skte hai or vise versa
#ex-> (2,6) so it will change to (6,2)
ares = arrd.transpose()
print(ares)

#shortcut method for transpose function that is simply using T


ared = arrd.T #same kaam karega jaise hamara transpose function kar rha tha
print(ared)
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.2:

[ 1 2 3 4 5 6 7 8 9 10 11 12]
[ 0 2 4 6 8 10 12]
[1. 2.25 3.5 4.75 6. ]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[[ 1 2]

27 | P a g e
[ 3 4]]

[[ 5 6]
[ 7 8]]

[[ 9 10]
[11 12]]]
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
[ 1 2 3 4 5 6 7 8 9 10 11 12]
[ 1 2 3 4 5 6 7 8 9 10 11 12]
[[ 1 7]
[ 2 8]
[ 3 9]
[ 4 10]
[ 5 11]
[ 6 12]]
[[ 1 7]
[ 2 8]
[ 3 9]
[ 4 10]
[ 5 11]
[ 6 12]]

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 4


#4th program of Mathmetical operations using numpy array
#we can add,subtract,multiply , divide two multidimensional array
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
arr_1 = np.arange(1,13).reshape(3,4)
arr_2 = np.arange(1,13).reshape(3,4)
print(arr_1)
print(arr_2)
#for addition(two methods)
print(arr_1 + arr_2) #yaha 1st element of arr_1 is added with 1st element of arr_2 and so on
print(np.add(arr_1,arr_2))

#for subtraction(two methods)


print(arr_1 - arr_2) #yaha 1st element of arr_1 is subtracted with 1st element of arr_2 and so on
print(np.subtract(arr_1,arr_2))

#for multiplication(two methods)


print(arr_1 * arr_2) #yaha 1st element of arr_1 is Multiplied with 1st element of arr_2 and so on
print(np.multiply(arr_1,arr_2))

#for division( two methods)


print(arr_1 / arr_2) #yaha 1st element of arr_1 is Multiplied with 1st element of arr_2 and so on
print(np.divide(arr_1,arr_2)) #output float me ayega

#max() -> if we have to find the max value in an array


print(arr_1.max())
#if we have to find at which index maximum value exists ......

28 | P a g e
#so for this we use argmax()
print(arr_1.argmax())

#agr hame har row/column me maximum value find karni hai toh iske liye hum max(axis) parameter denge
#for axis = 0 -> for column
#for axis = 1 -> for row
print(arr_1.max(axis = 0))
print(arr_1.max(axis = 1))

#same for minimum ............ min() , argmin(), min(axis - 0 or axis = 1)

#to sum all elements of matrix we use sum function


print(arr_1.sum())
#ab agr mujhe column ke across sum chahiye ya phir row ke across toh iske liye me sum me axis parameter ka
istemaal karunga
print(arr_1.sum(axis = 0 )) #for sum of columns
print(arr_1.sum(axis = 1))# for sum of rows

#we can find the mean/average of matrix using mean()


print(np.mean(arr_1))

#if we have to find the square root of each and every element of matrix we use sqrt function
print(np.sqrt(arr_1))

#to find the standard division of matrix


print(np.std(arr_1))

#to find the exponent of each element of matrix -> e^x


print(np.exp(arr_1))

#to find the log base e of each element of matrix


print(np.log(arr_1))

#to find the log base 10 of each element of matrix


print(np.log10(arr_1))
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.3:

[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 2 4 6 8]
[10 12 14 16]
[18 20 22 24]]
[[ 2 4 6 8]
[10 12 14 16]
[18 20 22 24]]
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
[[0 0 0 0]

29 | P a g e
[0 0 0 0]
[0 0 0 0]]
[[ 1 4 9 16]
[ 25 36 49 64]
[ 81 100 121 144]]
[[ 1 4 9 16]
[ 25 36 49 64]
[ 81 100 121 144]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
12
11
[ 9 10 11 12]
[ 4 8 12]
78
[15 18 21 24]
[10 26 42]
6.5
[[1. 1.41421356 1.73205081 2. ]
[2.23606798 2.44948974 2.64575131 2.82842712]
[3. 3.16227766 3.31662479 3.46410162]]
3.452052529534663
[[2.71828183e+00 7.38905610e+00 2.00855369e+01 5.45981500e+01]
[1.48413159e+02 4.03428793e+02 1.09663316e+03 2.98095799e+03]
[8.10308393e+03 2.20264658e+04 5.98741417e+04 1.62754791e+05]]
[[0. 0.69314718 1.09861229 1.38629436]
[1.60943791 1.79175947 1.94591015 2.07944154]
[2.19722458 2.30258509 2.39789527 2.48490665]]
[[0. 0.30103 0.47712125 0.60205999]
[0.69897 0.77815125 0.84509804 0.90308999]
[0.95424251 1. 1.04139269 1.07918125]]

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 5

#5th pro of NumpyArray Slicing


#BY HARSH SHUKLA (0901IO211023)
import numpy as np
mx = np.arange(1,101).reshape(10,10)
#if i want to access 1 element
print(mx[0,0]) #[row,column]
#and if we check dimension
print(mx[0,0].ndim) #if ndim is zero then the quantity is scalar

#if we want single row


print(mx[0])
#if we want single column
#[:,0] -> we want whole row of which column that is zero
print(mx[:,0]) #but ye column 1-D me aya
#hame ye 2-D me chahiye toh

30 | P a g e
print(mx[:,0:1]) #this is in 2-D how??
#check
print(mx[:,0:1].ndim)
#if we want 1,2,3 rows and 2,3,4 columns
print(mx[1:4,2:5])
#if we want all rows but only two colums
print(mx[:,0:2])
#if we want to access whole matrix
print(mx[:])
#two more methods to access whole matrix
print(mx[::])
print(mx[:,:])

#matrix me harek element ko store karne me kitna bit laga hai for this we use itmesize
print(mx.itemsize)#the output is 4 but how ??
#so phele hum dtype ke through ye dhek lete hai ki total kitne bit le rha hai ye matrix
print(mx.dtype) #so the output is 32
#so me divide 32/8 and ans is 4
print("BY HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.4:

1
0
[ 1 2 3 4 5 6 7 8 9 10]
[ 1 11 21 31 41 51 61 71 81 91]
[[ 1]
[11]
[21]
[31]
[41]
[51]
[61]
[71]
[81]
[91]]
2
[[13 14 15]
[23 24 25]
[33 34 35]]
[[ 1 2]
[11 12]
[21 22]
[31 32]
[41 42]
[51 52]
[61 62]
[71 72]
[81 82]
[91 92]]
[[ 1 2 3 4 5 6 7 8 9 10]
[ 11 12 13 14 15 16 17 18 19 20]
[ 21 22 23 24 25 26 27 28 29 30]
[ 31 32 33 34 35 36 37 38 39 40]
[ 41 42 43 44 45 46 47 48 49 50]

31 | P a g e
[ 51 52 53 54 55 56 57 58 59 60]
[ 61 62 63 64 65 66 67 68 69 70]
[ 71 72 73 74 75 76 77 78 79 80]
[ 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100]]
[[ 1 2 3 4 5 6 7 8 9 10]
[ 11 12 13 14 15 16 17 18 19 20]
[ 21 22 23 24 25 26 27 28 29 30]
[ 31 32 33 34 35 36 37 38 39 40]
[ 41 42 43 44 45 46 47 48 49 50]
[ 51 52 53 54 55 56 57 58 59 60]
[ 61 62 63 64 65 66 67 68 69 70]
[ 71 72 73 74 75 76 77 78 79 80]
[ 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100]]
[[ 1 2 3 4 5 6 7 8 9 10]
[ 11 12 13 14 15 16 17 18 19 20]
[ 21 22 23 24 25 26 27 28 29 30]
[ 31 32 33 34 35 36 37 38 39 40]
[ 41 42 43 44 45 46 47 48 49 50]
[ 51 52 53 54 55 56 57 58 59 60]
[ 61 62 63 64 65 66 67 68 69 70]
[ 71 72 73 74 75 76 77 78 79 80]
[ 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100]]
4
int32

BY HARSH SHUKLA
0901IO211023

Numpy Array - > 6

#8th pro of working with random data in NumpyArray


#so for working with random data first we have to import random library
#BY HARSH SHUKLA (0901IO211023)
import numpy as np
import random #me iska alias name nhi de skta hun
#this creates a 1-D array
print(np.random.random(1)) #random() -> (1 se 0 se beech me koi bhee value de dega)
#2-d array
print(np.random.random((3,3)))
#if i want only integer value between a particular range
print(np.random.randint(1,5)) #ek se 5 ke beach me koi bhee 1 value a jayegi but voh integer hogi
#2-D array of random integers
print(np.random.randint(1,5,(4,4)))
#3-d array of randome integers
print(np.random.randint(1,5,(3,3,4)))
#ab dikkat ho ye rhi hai ki bar bar radom array generate ho rha hai but agr me chahta hun ki jo random array
generate
#hua hai usko me vapas use karu
#toh uske liye hamare pass seed() function hota hai jo 2**32-1 values tak value la skta hai
np.random.seed(10)
print(np.random.randint(1,5,(4,4)))

32 | P a g e
np.random.seed(10)
print(np.random.randint(1,5,(4,4)))
#so agr hum dekho toh vapas vohi same random array a rha hai

#rand function
print(np.random.rand(3)) #so 1-d array create ho jayega or range (1,0) ke beech me koi bhee 3 numbers
print(np.random.rand(3,3)) #2-d array of size 3*3
print(np.random.rand(2,3,3)) #3-d array of size (3*3) * 2

#randn function
#ye humare random value deta hai (0,1) ke beech me but ye (+,-) values dono deta hai
print(np.random.randn(3)) #it returns the samples of standard normal distribution

#choice function
#ye hamare diye gaye sequence me se koi bhee ek value return kar dega
lst = [1,2,3,4]
print(np.random.choice(lst))
#clearing the concept of choice()
for i in range(20):
print(np.random.choice(lst))

#permutaion function
print(np.random.permutation(lst))# it returns the random permutation of given sequence
#clearing the concept of permutation()
for i in range(20):
print(np.random.permutation(lst))
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 4TH MACRO PROGRAM - > 1.5:

[0.38656949]
[[0.15817412 0.60901665 0.87186768]
[0.3439397 0.05934477 0.6286641 ]
[0.76638949 0.32837078 0.66510341]]
4
[[3 2 2 3]
[1 3 2 4]
[4 3 1 3]
[2 1 4 2]]
[[[1 4 1 2]
[1 3 4 3]
[1 2 3 1]]

[[2 1 2 4]
[3 4 1 2]
[1 4 2 1]]

[[3 3 4 3]
[3 1 3 4]
[2 4 1 1]]]
[[2 2 1 4]
[1 2 4 1]
[2 2 1 2]
[2 3 1 2]]
[[2 2 1 4]

33 | P a g e
[1 2 4 1]
[2 2 1 2]
[2 3 1 2]]
[0.16911084 0.08833981 0.68535982]
[[0.95339335 0.00394827 0.51219226]
[0.81262096 0.61252607 0.72175532]
[0.29187607 0.91777412 0.71457578]]
[[[0.54254437 0.14217005 0.37334076]
[0.67413362 0.44183317 0.43401399]
[0.61776698 0.51313824 0.65039718]]

[[0.60103895 0.8052232 0.52164715]


[0.90864888 0.31923609 0.09045935]
[0.30070006 0.11398436 0.82868133]]]
[ 0.1327083 -0.47614201 1.30847308]
1
1
2
1
4
1
1
3
1
3
3
1
4
2
1
4
2
3
3
2
3
[2 4 1 3]
[2 3 4 1]
[1 4 2 3]
[2 3 1 4]
[1 4 2 3]
[3 1 2 4]
[3 4 1 2]
[3 1 4 2]
[4 1 2 3]
[2 4 3 1]
[4 1 2 3]
[3 1 4 2]
[4 2 3 1]
[4 3 2 1]
[3 4 2 1]
[2 4 3 1]
[3 1 4 2]
[3 2 4 1]
[3 1 4 2]
[2 3 4 1]
[2 1 4 3]

34 | P a g e
HARSH SHUKLA
0901IO211023

MACRO PROGRAM 5TH

Pandas Series - > 1

#1st program of Pandas Series (introduction)


#to convert list data structure into pandas Series
import pandas as pd
lst = [1,2,3,6,9]
var = pd.Series(lst)
print(var)
print(type(var))
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.0:

0 1
1 2
2 3
3 6
4 9
dtype: int64
<class 'pandas.core.series.Series'>
HARSH SHUKLA
0901IO211023

Pandas Series - > 2

#6th program of Pandas Series


#to convert different data types into pandas Series like dictionary , single integer and so on

#doubt how to change the index of dictonary ............... ??


import pandas as pd
dic = {"J":"January","F":"Feburary","M":"March"}
var = pd.Series(dic,index = [1,2,3]) #if we have mixed data types then dtype field gives object as data type
print(var)
var = pd.Series(12,index = ["a"]) #if we have mixed data types then dtype field gives object as data type
#index paramter me humne list ke form me pass karna hai jp bhee index aap pass karoge.....
print(var)
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.1:

1 NaN
2 NaN
3 NaN
dtype: object
a 12
dtype: int64

35 | P a g e
HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 3

#9th program in pandas DataFrame


#to insert column in Pandas DataFrame using insert function which have 3 parameters
#1st parameter -> kis index pr rakhna hai naye column ko
#2nd paramter -> name of column
#3rd parameter -> data in that column
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var.insert(2,"C",[1,9,8,10])
var.insert(3,"D",[1.2,1.4,2.4,3])
print(var)
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.2:

0
0 1
1 3
2 4
3 5
4 6
<class 'pandas.core.frame.DataFrame'>
HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 4

#7th program of Python Pandas DataFrame


#using Arithmatic Operators in pandas DataFrame like additon , subtracion , multiplication and division , floor
division
#exponential
#if we add two data frames then the result of integer will be integer
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var["C"] = var["A"] + var["B"] #synatax to add two columns and generate thrid column(result)
print(var)

#8th program of python pandas dataFrame


#to use logical operators in DataFrame
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var["C"] = var["A"] != 2
var["D"] = var["B"] > 6
print(var)

36 | P a g e
#9th program in pandas DataFrame
#to insert column in Pandas DataFrame using insert function which have 3 parameters
#1st parameter -> kis index pr rakhna hai naye column ko
#2nd paramter -> name of column
#3rd parameter -> data in that column
import pandas as pd
dic = {"A":[1,2,3,4],"B":[5,6,7,8]}
var = pd.DataFrame(dic)
var.insert(2,"C",[1,9,8,10])
var.insert(3,"D",[1.2,1.4,2.4,3])
print(var)

print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.3:

A B C
0 1 5 6
1 2 6 8
2 3 7 10
3 4 8 12

A B C D
0 1 5 True False
1 2 6 False False
2 3 7 True True
3 4 8 True True

A B C D
0 1 5 1 1.2
1 2 6 9 1.4
2 3 7 8 2.4
3 4 8 10 3.0

HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 5

#1st program of merging of two data frames


#for merging of DataFrames 1 common id should be their
#means a common part that can be used to merge both DataFrames
import pandas as pd
# var1 = pd.DataFrame({"A":[1,2,3],"B":[3,4,5]})
# var2 = pd.DataFrame({"A":[1,2,3],"C":[6,7,8]})
# print(pd.merge(var1,var2,on="A"))
#agr me common data nhi deta hun toh
#so jitna data common hoga uske according merging hogi
var1 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
var2 = pd.DataFrame({"A":[1,2,3],"C":[6,7,8]})
print(pd.merge(var1,var2))#on is not compulsory
#how parameter NaN value ko bhee batata hai jo chut gai hai
print(pd.merge(var2,var1,how = "left", indicator= True))

37 | P a g e
print(pd.merge(var2,var1,how = "right",indicator = True))
#ab agr mere dono data frames de same keys hai means i am not talking about value of key only name of key is
same
#then if i merge their will no output reflected then what to do for this we use left_index = Ture and right_index
= True
var12 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
var23 = pd.DataFrame({"A":[1,2,3,5],"B":[6,7,8,9]})

print(pd.merge(var12,var23,left_index = True , right_index = True,suffixes = ["Name","id"])) #isse hoga ye ki


har key ki value reflect hogi
#but aisa karne se hamari key ka name ajjeb se ho jayega for this we will use suffixes to change the name of
key

#Concat -> common part nhi dhekte hai bus do Series or data frames ko join kar deta hai
#first we concat two series
s1 = pd.Series([1,2,3,4])
s2 = pd.Series([5,6,7,8])
print(pd.concat([s1,s2]))#ek khas bat ki jab hum do Series ko add kar rhe honge toh humme unko list ke
through pass karna hai
#we can also concat two DataFrames
var11 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
var22 = pd.DataFrame({"A":[1,2,3,5],"C":[6,7,8,9]})
print(pd.concat([var11,var22],join = "outer")) #outer by default hota hai inner se sub NaN hut jayega
print(pd.concat([var11,var22],join = "inner",axis = 1)) #axis 1 dene se column wise a raha hai or axis 0 dene se
row wise ata
#agr mujhe NaN wala data hatana hai toh uske liye hum join kar istemaal karenge

#join two data Frames


d1 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
d2 = pd.DataFrame({"C":[2,8,9,5],"D":[10,20,30,50]})
#join karrate vakat hum do data frames me same key nhi de skte hai
print(d1.join(d2))
d11 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]},index = ["a","b","c","d"])
d22 = pd.DataFrame({"C":[2,8],"D":[10,20]},index = ["a","b"])
print(d11.join(d22,how= "left"))
print(d11.join(d22,how= "inner"))
#hum join de saath how ka bhee istemaal kar skte hai
#how ke parameters -> left , right, inner(intersection ) , outer(union)
#agr hamari column ki value same ho jati hai join me toh toh ek error de dega toh iske liye hame left suffix or
right suffix ka use
#karna padega
d12 = pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]},index = ["a","b","c","d"])
d21 = pd.DataFrame({"A":[2,8],"D":[10,20]},index = ["a","b"])
print(d12.join(d21,rsuffix = "_21"))

#Append
#join me agr do column ke name same ho ja rhe the toh error a rha tha ya phir usko humko suffix ke through
solve karna pad rha tha
#but append me agr do column ka name bhee same hai toh koi dikkat nhi hai
a1= pd.DataFrame({"A":[1,2,3,4],"B":[3,4,5,6]})
a2 = pd.DataFrame({"A":[2,8],"D":[10,20]})
print(a1.append(a2,ignore_index = True))#ignore_index se hamari index sequence me ayegi........
print("HARSH SHUKLA")
print("0901IO211023")

38 | P a g e
OUTPUT OF 5TH MACRO PROGRAM - > 1.4:

A B C
0 1 3 6
1 2 4 7
2 3 5 8
A C B _merge
0 1 6 3 both
1 2 7 4 both
2 3 8 5 both
A C B _merge
0 1 6.0 3 both
1 2 7.0 4 both
2 3 8.0 5 both
3 4 NaN 6 right_only
AName BName Aid Bid
0 1 3 1 6
1 2 4 2 7
2 3 5 3 8
3 4 6 5 9
0 1
1 2
2 3
3 4
0 5
1 6
2 7
3 8
dtype: int64
A B C
0 1 3.0 NaN
1 2 4.0 NaN
2 3 5.0 NaN
3 4 6.0 NaN
0 1 NaN 6.0
1 2 NaN 7.0
2 3 NaN 8.0
3 5 NaN 9.0
A B A C
0 1 3 1 6
1 2 4 2 7
2 3 5 3 8
3 4 6 5 9
A B C D
0 1 3 2 10
1 2 4 8 20
2 3 5 9 30
3 4 6 5 50
A B C D
a 1 3 2.0 10.0
b 2 4 8.0 20.0
c 3 5 NaN NaN
d 4 6 NaN NaN
A B C D
a 1 3 2 10
b 2 4 8 20

39 | P a g e
A B A_21 D
a 1 3 2.0 10.0
b 2 4 8.0 20.0
c 3 5 NaN NaN
d 4 6 NaN NaN
C:\Users\hs081\PycharmProjects\Merging and Joining of DataFrames\main.py:59: FutureWarning: The
frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat
instead.
print(a1.append(a2,ignore_index = True))#ignore_index se hamari index sequence me ayegi........
A B D
0 1 3.0 NaN
1 2 4.0 NaN
2 3 5.0 NaN
3 4 6.0 NaN
4 2 NaN 10.0
5 8 NaN 20.0

HARSH SHUKLA
0901IO211023

Pandas DataFrames - > 6

#reshaping of pandas file ..(data Frame)


#means agr horizontal hai toh vertical bana denge ....
import pandas as pd
dic = {"days":[1,2,3,4,5,6],"eng":[12,14,15,17,13,10],"maths":[17,19,20,19,18,19]}
var = pd.DataFrame(dic)
print(var)
#abhi ye var horizontal me hai agr mujhe is var ko reshape karna hai means horizontal ko vertical me convert
karna hai toh
#uske liye me melt function ka istemaal karunga
print(pd.melt(var))
#here id acts as a key
print(pd.melt(var,id_vars = ["days"],var_name = "subject",value_name= "marks"))

#pivot function -> used for data arrangment and reshaping


#isme 2 paramters is must hai
#1st -> index and 2nd-> columns
dic1 =
{"days":[1,2,3,4,5,6],"Stu":["a","b","a","c","b","c"],"eng":[12,14,15,17,13,10],"maths":[17,19,20,19,18,19]}
var1 = pd.DataFrame(dic1)
print(var1.pivot(index = "days",columns = "Stu"))
#agr mujhe ek particular data chahiye toh iske liye me value keyword ka istemaal karunga
print(var1.pivot(index = "days",columns = "Stu",values = "eng"))
#agr mujhe koi arithmatic operation perform karna hai toh iske liye hum pivot_table function ka istemaal
karenge
#aggfun ke through me koi bhee operation perform karva skta hun
print(var1.pivot_table(index = "Stu",columns = "days",aggfunc = "min"))
#max,mean,sum etc.
print("HARSH SHUKLA")
print("0901IO211023")

OUTPUT OF 5TH MACRO PROGRAM - > 1.5:


days eng maths
0 1 12 17

40 | P a g e
1 2 14 19
2 3 15 20
3 4 17 19
4 5 13 18
5 6 10 19
variable value
0 days 1
1 days 2
2 days 3
3 days 4
4 days 5
5 days 6
6 eng 12
7 eng 14
8 eng 15
9 eng 17
10 eng 13
11 eng 10
12 maths 17
13 maths 19
14 maths 20
15 maths 19
16 maths 18
17 maths 19
days subject marks
0 1 eng 12
1 2 eng 14
2 3 eng 15
3 4 eng 17
4 5 eng 13
5 6 eng 10
6 1 maths 17
7 2 maths 19
8 3 maths 20
9 4 maths 19
10 5 maths 18
11 6 maths 19
eng maths
Stu a b c a b c
days
1 12.0 NaN NaN 17.0 NaN NaN
2 NaN 14.0 NaN NaN 19.0 NaN
3 15.0 NaN NaN 20.0 NaN NaN
4 NaN NaN 17.0 NaN NaN 19.0
5 NaN 13.0 NaN NaN 18.0 NaN
6 NaN NaN 10.0 NaN NaN 19.0
Stu a b c
days
1 12.0 NaN NaN
2 NaN 14.0 NaN
3 15.0 NaN NaN
4 NaN NaN 17.0
5 NaN 13.0 NaN
6 NaN NaN 10.0
eng maths
days 1 2 3 4 5 6 1 2 3 4 5 6
Stu

41 | P a g e
a 12.0 NaN 15.0 NaN NaN NaN 17.0 NaN 20.0 NaN NaN NaN
b NaN 14.0 NaN NaN 13.0 NaN NaN 19.0 NaN NaN 18.0 NaN
c NaN NaN NaN 17.0 NaN 10.0 NaN NaN NaN 19.0 NaN 19.0

HARSH SHUKLA
0901IO211023

42 | P a g e

You might also like