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

PRACTICAL FILE IP - Copy (1)

Uploaded by

ARSH Chawaria
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

PRACTICAL FILE IP - Copy (1)

Uploaded by

ARSH Chawaria
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

#1 Write a program to create a series object using

individual strings.

CODE:
import pandas as pd
ser = pd.Series(["Teacher","No","1"])
print(ser)

OUTPUT:
0 Teacher
1 No
2 1
dtype: object
#2 Write a program to create a Series using ndarray
having 5 elements from 22 to 48 and also tiling it
twice.

CODE:
import pandas as pd
import numpy as np
list = np.linspace(22,35,5)
ser = pd.Series(np.tile(list,2))
print(ser)

OUTPUT:
0 22.00
1 25.25
2 28.50
3 31.75
4 35.00
5 22.00
6 25.25
7 28.50
8 31.75
9 35.00
dtype: float64

#3 Write a program to create a Series that stores the


total medals for games in every 2 years from decade
2020-2029.
CODE:
import pandas as pd
med = [150,200,180,195,210]
ser = pd.Series(med,index=range(2020,2029,2))
print(ser)

OUTPUT:
2020 150
2022 200
2024 180
2026 195
2028 210
dtype: int64

#4 Create a Series with 9 elements and print upper 7


elements and last 5 elements only.

CODE:
import pandas as pd
ser = pd.Series([3,6,9,12,15,18,21,24,27])
print(ser.head(7))
print(ser.tail())

OUTPUT:
0 3 4 15
1 6 5 18
2 9 6 21
3 12 7 24
4 15 8 27
5 18 dtype: int64
6 21
dtype: int64

#5 Population of four metro cities in a series and


Average Income of four metro cities in series are
taken. Calculate the Per-Capita Income for each of the
metro cities
CODE:
import pandas as pd
import numpy as np
population=pd.Series([338927986,217691836,15663
1392,121328063],index=['Delhi','Mumbai','Kolkata','
Chennai'])
print("Population In Four Metro Cities:")
print(population)
avgincome=pd.Series([850878126918368,17216781
0927986,752617843280631,422678463139217],inde
x =['Delhi','Mumbai','Kolkata','Chennai'])
print("Average Income Of The Cities:")
print(avgincome)
percapita = PerCapita Income:
avgincome/population Delhi
2.510498e+06
print("PerCapita Income:") Mumbai
print(percapita) 7.908786e+05
Kolkata
4.805026e+06
Chennai
OUTPUT:

Average Income Of The Population In Four Metro Cities:


Cities: Delhi 338927986
Delhi 850878126918368 Mumbai 217691836
Mumbai 172167810927986 Kolkata 156631392
Kolkata 752617843280631 Chennai 121328063
Chennai
422678463139217
#6 Write a program to create a dataframe from 2D-
List. Specify your own index labels.

CODE:
import pandas as pd
list = [[25,34,88],[45,90,67],[56,60,89]]
df =
pd.DataFrame(list,index=["row1","row2","row3"])
print(df)

OUTPUT:

0 1 2
row1 25 34 88
row2 45 90 67
row3 56 60 89

#7 Create the Dataframe Sales containing years


(2015,2016,2017,2018) wise sales figures for 5
salesperson in INR. Use the years as column labels and
salesperson as row labels. Also show transpose of the
dataframe formed.
CODE:
import pandas as pd
SaleDict = {2014:
[100.5,150.8,200.9,30000,40000],2015:
[12000,18000,22000,30000,45000],2016:
[20000,50000,70000,100000,125000],2017:
[50000,60000,70000,80000,90000]}
Sales = pd.DataFrame(SaleDict,index =
["Madhu","Kusum","Kinshuk","Ankit","Shruti"])
print('DataFrame Sales:')
print(Sales)
print('Transpose Of DataFrame Sales')
print(Sales.T)

OUTPUT: DataFrame Sales:


2014 2015 2016
2017
Madhu 100.5 12000 20000
50000
Kusum 150.8 18000 50000
60000
Kinshuk 200.9 22000 70000
70000
Ankit 30000.0 30000 100000
Transpose Of 80000
DataFrame Sales
Madhu Shruti 40000.0
Kusum 45000 125000
Kinshuk Ankit
Shruti 90000
2014 100.5 150.8 200.9 30000.0
40000.0

#8 Create a 2015 12000.0 18000.0 22000.0


45000.0
30000.0

Series and 2016 20000.0 50000.0 70000.0 100000.0


125000.0
using it create 2017 50000.0 60000.0 70000.0 80000.0
90000.0
other 2 series
with squaring it and twice of it.

CODE:
import pandas as pd
ser = pd.Series([5,3,12,9,14])
ser2 = ser**2
ser3 = ser*2
print(ser)
print(ser2)
print(ser3)

OUTPUT:

0 5 0 25 0 10
1 3 1 9 1 6
2 12 2 144 2 24
3 9 3 81 3 18
4 14 4 196 4 28
dtype: int64 dtype: int64 dtype: int64

#9 Create a DataFrame Sales with column labels as


year and names as row indexes.
CODE:
import pandas as pd
SD = {2014:
{'Madhu':100.5,'Kusum':150.5,'Kinshuk':200.9,'Ankit':
30000,'Shruti':40000},2015:
{'Madhu':12000,'Kusum':18000,'Kinshuk':22000,'Anki
t':30000,'Shruti':45000},2016:
{'Madhu':20000,'Kusum':50000,'Kinshuk':70000,'Anki
t':100000,'Shruti':125000},2017:
{'Madhu':50000,'Kusum':60000,'Kinshuk':70000,'Anki
t':80000,'Shruti':90000}}
Sales = pd.DataFrame(SD)
print(Sales)

OUTPUT:

2014 2015 2016


2017
Madhu 100.5 12000 20000
50000
Kusum 150.5 18000 50000
60000
Kinshuk 200.9 22000 70000 70000
Ankit 30000.0 30000 100000 80000
Shruti 40000.0 45000 125000 90000

#10 Using iterrows()to extract data from DataFrame


row wise.
CODE:
import pandas as pd
Sales = {'yr1':
{'Qty1':34500,'Qty2':56000,'Qty3':47000,'Qty4':4900
0},'yr2':
{'Qty1':44900,'Qty2':46100,'Qty3':57000,'Qty4':5900
0},'yr3':
{'Qty1':54500,'Qty2':51000,'Qty3':57000,'Qty4':5850
0}}
dfS = pd.DataFrame(Sales)
for (row,rowSeries) in dfS.iterrows():
print("Row index:",row)
print("Containig:")
print(rowSeries)

OUTPUT:
Row index: Qty1 Row index: Qty3
Containig: Containig:
yr1 34500 yr1 47000
yr2 44900 yr2 57000
yr3 54500 yr3 57000
Name: Qty1, dtype: int64 Name: Qty3, dtype: int64
Row index: Qty2 Row index: Qty4
Containig: Containig:
yr1 56000 yr1 49000
yr2 46100 yr2 59000
yr3 51000 yr3 58500
Name: Qty2, dtype: int64 Name: Qty4, dtype: int64

#11 Create two dataframes and perform addition and


subtraction among the dataframes.
CODE:
import pandas as pd
df1 = pd.DataFrame({"A":[1,4,7],"B":[2,6,8],"C":
[3,6,9]})
df2 = pd.DataFrame({"A":[100,200],"B":
[300,400],"C":[500,600]})
print(df1.add(df2))
print(df1.radd(df2))
print(df1.sub(df2))
print(df1.rsub(df2))

OUTPUT:
A B C A B C
0 101.0 302.0 0 -99.0 -298.0 -497.0
503.0 1 -196.0 -394.0 -594.0
1 204.0 406.0 606.0 2 NaN NaN NaN
2 NaN NaN NaN

A B C A B C
0 101.0 302.0 0 99.0 298.0 497.0
503.0 1 196.0 394.0 594.0
1 204.0 406.0 2 NaN NaN NaN
606.0
2 NaN NaN NaN

#12 Create two dataframes and perform


multiplication and division among the dataframes.
CODE:
import pandas as pd
df1 = pd.DataFrame({"A":[10,40,30],"B":
[50,20,70],"C":[60,90,80]})
df2 = pd.DataFrame({"A":[1000,2000,3000],"B":
[5000,4000,6000]})
print(df1.mul(df2))
print(df1.div(df2))
print(df1.rdiv(df2))

OUTPUT:

A B C A B C
0 10000 250000 NaN 0 0.01 0.010000 NaN
1 80000 80000 NaN 1 0.02 0.005000 NaN
2 90000 420000 NaN 2 0.01 0.011667 NaN

A B C
0 100.0 100.000000 NaN
1 50.0 200.000000 NaN
#13 Create a demo DataFrame for environment and
use functions min(),max().
CODE:
import pandas as pd
data = {"Flora": [1200, 900, 1500, 600,
800],"Fauna": [450, 700, 600, 300, 550],"Natural
Reserves": [15, 10, 20, 5, 8]}
countries = ["India", "Australia", "Brazil", "Canada",
"South Africa"]
ent_df = pd.DataFrame(data, index=countries)
print(ent_df)
print(ent_df.min())
print(ent_df.max())

OUTPUT:

Flora Fauna Natural


Reserves
India 1200 450
15
Australia 900 700
10
Brazil 1500 600
20
Canada 600 300
Flora
5 600 Flora 1500
Fauna
South Africa 800 550 Fauna 8 700
300 Natural Reserves 20
Natural Reserves 5 dtype: int64
dtype: int64
#14 Create a DataFrame for agriculture and perform
mean(), median() and mode() for it.
CODE:
import pandas as pd
data = {"Fruits": [150, 200, 180, 220, 170],"Rice":
[1200, 950, 1100, 800, 700],"Wheat": [900, 850, 950,
600, 700],"Pulses": [300, 250, 280, 220, 260]}
states = ["Punjab", "West Bengal", "Maharashtra",
"Tamil Nadu", "Uttar Pradesh"]
agri_df = pd.DataFrame(data, index=states)
print(agri_df)
print(agri_df.mean())
print(agri_df.mean(axis=1))
print(agri_df.median())
print(agri_df.median(axis=1))
print(agri_df.mode())
print(agri_df.mode(axis=1))

OUTPUT:

Fruits Rice Wheat


Pulses
Punjab 150 1200 900
300
West Bengal 200 950 850
250
Maharashtra 180 1100 950
280
Fruits 184.0 Punjab
Rice 950.0 637.5
Wheat 800.0 West Bengal
Pulses 262.0 562.5
dtype: float64 Maharashtra
627.5
Tamil Nadu
#15 Use function Quantile creating a demo dataframe
on your own.
CODE:
import pandas as pd
data = {"Math": [85, 90, 78, 88, 76],"Science": [92,
89, 84, 91, 80],"English": [88, 76, 85, 90,
89],"History": [75, 80, 72, 85, 78],"Geography": [82,
88, 79, 84, 77]}
students = ["Student A", "Student B", "Student C",
"Student D", "Student E"]
sdf = pd.DataFrame(data, index=students)
print(sdf.quantile([0.25,0.5,0.75,1.0]))
print(sdf.quantile([0.25,0.5,0.75,1.0],axis=1))

OUTPUT:

Math Science English History Geography


0.25 78.0 84.0 85.0 75.0 79.0
0.50 85.0 89.0 88.0 78.0 82.0
0.75 88.0 91.0 89.0 80.0 84.0
1.00 90.0 92.0 90.0 85.0 88.0

Student A Student B Student C Student D Student


E
0.25 82.0 80.0 78.0 85.0
77.0
0.50 85.0 88.0 79.0 88.0
78.0
0.75 88.0 89.0 84.0 90.0
80.0
1.00 92.0 90.0 85.0 91.0
89.0

#16 Create a demo dataframe use describe().


CODE:
import pandas as pd
data = {"Population": [85, 125, 110, 70,
95],"Temperature ": [32, 28, 30, 35, 29],"Literacy
Rate": [88, 90, 85, 82, 87],"Tourist Visits": [10, 15, 8,
5, 12]}
cities = ["Delhi", "Mumbai", "Chennai", "Jaipur",
"Kolkata"]
cdf = pd.DataFrame(data, index=cities)
print(cdf)
print(cdf.describe())

OUTPUT:

Population Temperature Literacy Rate Tourist


Visits
Delhi 85 32 88
10
Mumbai 125 28 90
15
Chennai 110 30 85
8
Jaipur 70 35 82
5 Population Temperature Literacy Rate Tourist
Visits
Kolkata 95 29 87
count
12 5.00000 5.000000 5.00000
5.000000
mean 97.00000 30.800000 86.40000
10.000000
std 21.38925 2.774887 3.04959
3.807887
min 70.00000 28.000000 82.00000
5.000000
25% 85.00000 29.000000 85.00000
8.000000
50% 95.00000 30.000000 87.00000
10.000000
75% 110.00000 32.000000 88.00000
12.000000
max 125.00000 35.000000 90.00000
15.000000
#17 Create a bar graph showing the medals won by
countries. Include appropriate labels for the x-axis, y-
axis, and a title.
CODE:
import matplotlib.pyplot as plt
import pandas as pd
plt.title("Medals Won")
plt.xlabel("Countries")
plt.ylabel("No. Of Medals")
df = pd.DataFrame({"Gold":[80,45,26,15],"Silver":
[59,45,20,40],"Bronze":[59,46,20,27],"Total":
[198,136,66,82]},index=['Australia','England','India','
Canada'])
df.plot(kind='bar')
plt.show()

OUTPUT:

#18 Create
a line
graph
showing
graph for Sin(x), Cos(x) and Tan(x) for each of the
following. Give suitable title and legend.
CODE:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0.,10,0.1)
a = np.sin(x)
b = np.cos(x)
c = np.tan(x)
plt.figure(figsize=(8, 4))
plt.plot(x,a,color='b',linestyle='dashed',linewidth=2)
plt.plot(x,b,color='r',linestyle='dotted',linewidth=2)
plt.plot(x,c,color='g',linestyle='dashdot')
plt.title("Wave")
plt.xlabel("x")
plt.ylabel("Function")
plt.legend()
plt.ylim(-2,2)
plt.show()

OUTPUT:
#19 Create a scatter chart for random values.
CODE:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randint(1,100,size=(300,))
y = np.random.randint(1,100,size=(300,))
color = ['r','b','c','m','g','k']*(len(x)//6)
plt.scatter(x,y,c=color)
plt.title("Scatter Values View")
plt.xlabel("X values")
plt.ylabel("Y label")
plt.show()

OUTPUT:
#20 Create a horizontal bar chart showing heights of 6
different persons.
CODE:
import matplotlib.pyplot as plt
heights = [5.2,6,5.10,5.5,5,6.2]
names =
['Aarav','Ananya','Kavya','Ishaan','Priya','Veer']
plt.barh(names,heights,color=['r','b','c','m','g','y'])
plt.title("Height")
plt.xlabel("Heights")
plt.ylabel("Names")
plt.xlim(4.5,6.5)
plt.show()

OUTPUT:
#21 Consider a TSS school collection by 6
sections(A,B,C,D,E,F). Create a pie chart showing the
collection percentage wise. Also explode A,C,D
sections.
CODE:
import matplotlib.pyplot as plt
col = [9900,15500,11300,7900,18600,8300]
sec = ['A','B','C','D','E','F']
exp = [0.2,0,0.1,0.3,0,0]
plt.title("Collection By Sections")
plt.axis("equal")
plt.pie(col,labels=sec,explode=exp,colors=['cyan','go
ld','violet','lightgreen','pink','silver'])
plt.show()

OUTPUT:

#22
Import
CSV
text
file
from
desktop as reference. Also print it without header and
with column indexes as EmpNo.
CODE:
import pandas as pd
df1 = pd.read_csv("C:\\Users\\blsro\\OneDrive\\
Desktop\\Employee.txt")
print(df1)
df2 = pd.read_csv("C:\\Users\\blsro\\OneDrive\\
Desktop\\Employee.txt",header=None,skiprows=1)
print(df2)
df3 = pd.read_csv("C:\\Users\\blsro\\OneDrive\\
Desktop\\Employee.txt",index_col="EmpNo ")
print(df3)

OUTPUT:

EmpNo Name Designation


Salary
0 1001 Trupti Manage 56000
1 1002 Raziya Manager 55900
2 1003 Simran Clerk 35000
3 1004 Silviya PR Officer 25000
4 1005 Suji Analyst 31000

0 1 2 3
#23 Create a Dataframe and save it using a csv file.
CODE:
import numpy as np
import pandas as pd
a = {"Name":
['Purv','Paschim','Dakshin','Uttar','Kendriya','Rural'],"P
roduct":
['Oven','AC','AC','Oven','TV','Tubewell'],"Target":
[56000.00,70000.00,np.NaN,75000.00,60000.00,np.
NaN],"Sales":
[58000.00,68000.00,np.NaN,78000.00,61000.00,np.
NaN]}
adf =
pd.DataFrame(a,index=['SecA','SecB','SecC','SecD','S
ecE','SecF'])
print(adf)
adf.to_csv("C:\\Users\\blsro\\OneDrive\\Desktop\\
Sales.txt")

OUTPUT:

#24 Establish connection between mysql and python


and display a table using it.
CODE:
import pandas as pd
import mysql.connector as sq
mycon=
sq.connect(host='localhost',user='root',password='m
ypass',database='contact')
cursor = mycon.cursor()
Name Product Target
Sales
SecA Purv Oven 56000.0
58000.0
SecB Paschim AC 70000.0
68000.0
SecC Dakshin AC NaN
NaN
SecD Uttar Oven 75000.0
78000.0 if
SecE Kendriya TV 60000.0
61000.0
SecF Rural Tubewell NaN NaN

mycon.is_connected():
print('connected successfully')
bdf = pd.read_sql("select * from contact;",mycon)
print(bdf)

OUTPUT:

connected successfully
contact_id name phone
email
0 C001 Rajesh Kumar 9876543210
[email protected]
1 C002 Anjali Sharma 8765432109
[email protected]
2 C003 Mohammed Iqbal 7654321098
[email protected]
3 C004 Priya Reddy None
[email protected]
4 C005 Amit Verma 9123456789
[email protected]

#25 Establish connection between mysql and python


and also create a database and a table using it.
CODE:
import mysql.connector as sq
mycon=sq.connect(host='localhost',user='root',pass
word='mypass')
cursor = mycon.cursor()
if mycon.is_connected():
print('connected successfully')
a = "create database if not exists library;"
cursor.execute(a)
print("Database Created Successfully")
mycon.database="library"
b = "create table if not exists books(book_id
varchar(10) primary key,title varchar(20) NOT
NULL,genre varchar(20),publication_year int);"
cursor.execute(b)
print("Table Books Created Successfully")

OUTPUT: connected successfully


Database Created Successfully
Table Books Created Successfully
#26 Enter the Data in the table created in the previous
program.
CODE:
import mysql.connector as sq
mycon=
sq.connect(host='localhost',user='root',password='m
ypass',database='library')
cursor = mycon.cursor()
if mycon.is_connected():
print('connected successfully')
book_id = input("Enter the book_id:")
title = input("Enter the Title of the Book:")
genre = input("Enter the Genre:")
pub_year = input("Enter the Publication Year:")
val = (book_id,title,genre,pub_year)
input = "insert into books values(%s,%s,%s,%s)"
cursor.execute(input,val)
mycon.commit()
print("Record Added Successfully")

OUTPUT:

connected successfully
Enter the book_id:101
Enter the Title of the Book:Dune
Enter the Genre:Science-Fiction
Enter the Publication Year:1965
Record Added Successfully

You might also like