Tuesday, November 16, 2021

List of Practical Question For Class 12 IP - Python

12 IP

1.Write a Python program to convert a dictionary to a Pandas series. Sample Series:
Dictionary:{'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 800}
Converted series:
a 100
b 200
c 300
d 400
e 800
dtype: int64

In [1]:
import pandas as pd

dc={'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 800}
sr=pd.Series(data=dc)
print(sr)
a    100
b    200
c    300
d    400
e    800
dtype: int64

2.Create a panda’s series from a numpy array.(Take array values of your choice).

In [8]:
import pandas as pd 
import numpy as np
ls=[12,13,14,15,16,17]
arr=np.array(ls)
sr=pd.Series(data=arr)
print(sr)
0    12
1    13
2    14
3    15
4    16
5    17
dtype: int32

3. Write a Pandas program to add, subtract, multiple and divide two Pandas Series.

In [4]:
import pandas as pd

ls=[10,11,12,13,14,15]
ls1=[1,2,3,4,5,6]
sr1=pd.Series(ls)
sr2=pd.Series(ls1)

print(sr1)
print(sr2)
print("SUM: \n",sr1+sr2)
print("Diffrence: \n",sr1-sr2)
print("Multiply: \n",sr1*sr2)
print("Divide: \n",sr1+sr2)
0    10
1    11
2    12
3    13
4    14
5    15
dtype: int64
0    1
1    2
2    3
3    4
4    5
5    6
dtype: int64
SUM: 
 0    11
1    13
2    15
3    17
4    19
5    21
dtype: int64
Diffrence: 
 0    9
1    9
2    9
3    9
4    9
5    9
dtype: int64
Multiply: 
 0    10
1    22
2    36
3    52
4    70
5    90
dtype: int64
Divide: 
 0    11
1    13
2    15
3    17
4    19
5    21
dtype: int64

4.Write a program to sort the element of Series S1 into S2(Take any series of of choice).

In [7]:
import pandas as pd

ls=[10,1,13,12,5,15]

sr1=pd.Series(ls)
print("Original Series: \n",sr1)
sr2=sr1.sort_values()
print("Sorted Series: \n", sr2)
Original Series: 
 0    10
1     1
2    13
3    12
4     5
5    15
dtype: int64
Sorted Series: 
 1     1
4     5
0    10
3    12
2    13
5    15
dtype: int64

5.Create two dataframes using the following two Dictionaries. Merge the two dataframes and append the second dataframe as a new column to the first dataframe on the basis of the manufacturing company’s name.

Car_Price = {'Company': ['Toyota', 'Honda', 'BMW', 'Audi'], 'Price': [23845, 17995, 135925 , 71400]}
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMW', 'Audi'], 'horsepower': [141, 80, 182 , 160]}

In [11]:
import pandas as pd

Car_Price = {'Company': ['Toyota', 'Honda', 'BMW', 'Audi'], 'Price': [23845, 17995, 135925 , 71400]}
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMW', 'Audi'], 'horsepower': [141, 80, 182 , 160]}

df1=pd.DataFrame(Car_Price)
df2=pd.DataFrame(car_Horsepower)
print(df1,"\n")
print(df2,"\n")

print("DataFrame Merge operation \n",df1.merge(df2))
  Company   Price
0  Toyota   23845
1   Honda   17995
2     BMW  135925
3    Audi   71400 

  Company  horsepower
0  Toyota         141
1   Honda          80
2     BMW         182
3    Audi         160 

DataFrame Merge 
   Company   Price  horsepower
0  Toyota   23845         141
1   Honda   17995          80
2     BMW  135925         182
3    Audi   71400         160

6.Create a Data Frame Expenditure where each row contains the item category, item name, and expenditure.

</table>

In [12]:
import pandas as pd
data={
    
    "item_category":["Groceries","Groceries","Groceries","cloth","cloth","Maintenance","Maintenance"],
    "item_name":["Rice","Milk","Vegetable","T shirt","Jeans","Electricity","Water"],
    "Expenditure":[1500,1000,2500,1000,2500,500,9000]
}
df=pd.DataFrame(data=data)
print(df)
  item_category    item_name  Expenditure
0     Groceries         Rice         1500
1     Groceries         Milk         1000
2     Groceries    Vegetable         2500
3         cloth      T shirt         1000
4         cloth        Jeans         2500
5   Maintenance  Electricity          500
6   Maintenance        Water         9000

7.Write a Pandas program to select the rows where the height is not known, i.e. is NaN.
'name': ['Asha', 'Radha', 'Kamal', 'Divy', 'Anjali'],
'height': [ 5.5, 5, np.nan, 5.9, np.nan],
'age': [11, 23, 22, 33, 22]

In [8]:
import pandas as pd
import numpy as np
data={
    'name': ['Asha', 'Radha', 'Kamal', 'Divy', 'Anjali'],
    'height': [ 5.5, 5, np.nan, 5.9, np.nan],
    'age': [11, 23, 22, 33, 22]
}

df=pd.DataFrame(data=data)
print(df)
df[df["height"].isna()]
     name  height  age
0    Asha     5.5   11
1   Radha     5.0   23
2   Kamal     NaN   22
3    Divy     5.9   33
4  Anjali     NaN   22
Out[8]:
Item Category Item name Expenditure
Groceries Rice 1500
Groceries Milk 1000
Groceries Vegetable 2500
Cloth T shirt 1000
Cloth Jeans 2500
Maintenance Electricity 500
Maintenance Water 9000
name height age
2 Kamal NaN 22
4 Anjali NaN 22

8.Write a Pandas program to select the name of persons whose height is between 5 to 5.5 (both values inclusive)
'name': ['Asha', 'Radha', 'Kamal', 'Divy', 'Anjali'],
'height': [ 5.5, 5, np.nan, 5.9, np.nan],
'age': [11, 23, 22, 33, 22]

In [15]:
import pandas as pd

data={
    'name': ['Asha', 'Radha', 'Kamal', 'Divy', 'Anjali'],
'height': [ 5.5, 5, np.nan, 5.9, np.nan],
'age': [11, 23, 22, 33, 22]
     }
df=pd.DataFrame(data=data)
print(df)
df[(df["height"]>=5) & (df["height"]<=5.5) &(df["height"].notna())]
     name  height  age
0    Asha     5.5   11
1   Radha     5.0   23
2   Kamal     NaN   22
3    Divy     5.9   33
4  Anjali     NaN   22
Out[15]:
name height age
0 Asha 5.5 11
1 Radha 5.0 23

9.Four series objects temp1, temp2, temp3 and temp4 store the temperature of week1, week2, week3 and week4 respectively. Create a a dataframe from these four series objects where the indexes should be “Sunday”,”Monday”,……..,”Saturday” and columns should be ‘week1’, ‘week2’,’week3’ and ‘week4’.

In [31]:
import pandas as pd

tmp1=pd.Series([32,31,30,31,30,33,32])
tmp2=pd.Series([32,31,30,31,30,33,32])
tmp3=pd.Series([32,31,30,31,30,33,32])
tmp4=pd.Series([32,31,30,31,30,33,32])

data={"week1":tmp1,"week2":tmp2,"week3":tmp3,"week4":tmp4}

df=pd.DataFrame(data)
df.index=["sunday","monday","tuesday","wednesday","thusday","friday","satrday"]
print(df)
           week1  week2  week3  week4
sunday        32     32     32     32
monday        31     31     31     31
tuesday       30     30     30     30
wednesday     31     31     31     31
thusday       30     30     30     30
friday        33     33     33     33
satrday       32     32     32     32

10.From the dataframe object created in previous question, write a script to calculate :
a)Average temperature for each day of week I.e. average temperature for Mondays, Tuesday and so on
b)Average temperature per week
c)Average temperature of whole month

In [42]:
import pandas as pd
import numpy as np

tmp1=pd.Series([32,31,30,31,30,33,32])
tmp2=pd.Series([32,31,30,31,30,33,32])
tmp3=pd.Series([32,31,30,31,30,33,32])
tmp4=pd.Series([32,31,30,31,30,33,32])

data={"week1":tmp1,"week2":tmp2,"week3":tmp3,"week4":tmp4}

df=pd.DataFrame(data)
df.index=["sunday","monday","tuesday","wednesday","thusday","friday","satrday"]
print(df)
print()

print("Average temperature day wise: \n",df.mean(axis=1))
print()
print("Average temperature  wise: \n",df.mean())
print()
print("Average temperature of whole month: \n",np.mean(df.mean()))
           week1  week2  week3  week4
sunday        32     32     32     32
monday        31     31     31     31
tuesday       30     30     30     30
wednesday     31     31     31     31
thusday       30     30     30     30
friday        33     33     33     33
satrday       32     32     32     32

Average temperature day wise: 
 sunday       32.0
monday       31.0
tuesday      30.0
wednesday    31.0
thusday      30.0
friday       33.0
satrday      32.0
dtype: float64

Average temperature  wise: 
 week1    31.285714
week2    31.285714
week3    31.285714
week4    31.285714
dtype: float64

Average temperature of whole month: 
 31.285714285714285

11.Given three dataframes namely Sales15, sales16 and Sales17 storing quarter wise sales of items ‘Beverages’, ‘Milk’, ‘Snack items’, ‘Icecreams’ and ‘Bakery items’. Write a script that prints the following:
a)Maximum yearly sales item-wise
b)Maximum Quarterly sales for an item across three years(eg. ‘Snack item’ had maximum sales in Quarter 3 of year 2017)
c)Average sales Quarter-wise for all items year wise.
d)Average sales Quarter-wise for all items for all years.

In [35]:
import pandas as pd
import numpy as np
sales15dt={ 'Beverages':[12,45,49,48], 
           'Milk':[12,13,14,15], 
           'snack items':[45,48,47,49],
           'icecream':[23,24,25,26],
           'bakery items':[36,35,39,34]}
dfsales15=pd.DataFrame(data=sales15dt,index=['qrt1','qtr2','qtr3','qtr4'])

sales16dt={ 'Beverages':[13,40,48,48], 
           'Milk':[12,18,14,17], 
           'snack items':[45,58,47,79],
    'icecream':[23,24,2,26],
           'bakery items':[3,35,39,34]}
dfsales16=pd.DataFrame(data=sales16dt,index=['qrt1','qtr2','qtr3','qtr4'])

sales17dt={ 'Beverages':[12,45,49,48], 
           'Milk':[78,13,17,15], 
           'snack items':[45,48,47,39],
           'icecream':[25,24,25,26],
           'bakery items':[37,35,39,34]}
dfsales17=pd.DataFrame(data=sales17dt,index=['qrt1','qtr2','qtr3','qtr4'])
print("Sales of 2015: \n\n",dfsales15);print()
print("Sales of 2016: \n\n",dfsales16);print()
print("Sales of 2017: \n\n",dfsales17);print()

# Maximum yearly sales item-wise----------------------------------------------------------------------
print("------------------------------Maximum yearly sales item-wise------------------------------")
data1={"2015":dfsales15.max(), "2016":dfsales16.max(), "2017":dfsales17.max()}
df1=pd.DataFrame(data1)

for i,j in df1.iterrows():
    print("--------------------------------------------------------------------------------------")
    print("item: ",i)
    print(j[j.values==j.max()])
    
print("------------------------------Maximum quaterly sales item-wise------------------------------")
Sales of 2015: 

       Beverages  Milk  snack items  icecream  bakery items
qrt1         12    12           45        23            36
qtr2         45    13           48        24            35
qtr3         49    14           47        25            39
qtr4         48    15           49        26            34

Sales of 2016: 

       Beverages  Milk  snack items  icecream  bakery items
qrt1         13    12           45        23             3
qtr2         40    18           58        24            35
qtr3         48    14           47         2            39
qtr4         48    17           79        26            34

Sales of 2017: 

       Beverages  Milk  snack items  icecream  bakery items
qrt1         12    78           45        25            37
qtr2         45    13           48        24            35
qtr3         49    17           47        25            39
qtr4         48    15           39        26            34

------------------------------Maximum yearly sales item-wise------------------------------
--------------------------------------------------------------------------------------
item:  Beverages
2015    49
2017    49
Name: Beverages, dtype: int64
--------------------------------------------------------------------------------------
item:  Milk
2017    78
Name: Milk, dtype: int64
--------------------------------------------------------------------------------------
item:  snack items
2016    79
Name: snack items, dtype: int64
--------------------------------------------------------------------------------------
item:  icecream
2015    26
2016    26
2017    26
Name: icecream, dtype: int64
--------------------------------------------------------------------------------------
item:  bakery items
2015    39
2016    39
2017    39
Name: bakery items, dtype: int64
------------------------------Maximum quaterly sales item-wise------------------------------
--------------------------------------------------------------------------------------
item:  Beverages
qrt1    12
qtr2    45
qtr3    49
qtr4    48
Name: Beverages, dtype: int64
--------------------------------------------------------------------------------------
item:  Milk
qrt1    12
qtr2    13
qtr3    14
qtr4    15
Name: Milk, dtype: int64
--------------------------------------------------------------------------------------
item:  snack items
qrt1    45
qtr2    48
qtr3    47
qtr4    49
Name: snack items, dtype: int64
--------------------------------------------------------------------------------------
item:  icecream
qrt1    23
qtr2    24
qtr3    25
qtr4    26
Name: icecream, dtype: int64
--------------------------------------------------------------------------------------
item:  bakery items
qrt1    36
qtr2    35
qtr3    39
qtr4    34
Name: bakery items, dtype: int64

1.The table shows passenger car fuel rates in miles per gallon for several years. Make a LINE GRAPH of the data. During which year period did the fuel rate decrease?
YEAR: 2000 2002 2004 2006
RATE: 21.0 20.7 21.2 21.6

In [1]:
import matplotlib.pyplot as plt
yr=[2000,2002,2004,2006]
rt=[21.0,20.7,21.2,21.6]
plt.plot(yr,rt)
plt.show()

2.Draw the histogram based on the Production of Wheat in different Years
Year: 2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018
Production': 4, 6, 7, 15, 24, 2, 19, 5, 16, 4

In [8]:
import matplotlib.pyplot as plt

import pandas as pd 
import matplotlib.pyplot as plt 
data={'Year':[2000,2002,2004,2006,2008,2010,2012,2014,2016,2018],
      'Production':[4,6,7,15,24,2,19,5,16,4]} 
d=pd.DataFrame(data) 
print(d) 
x=d.hist(column='Production',bins=5,grid=True) 
plt.show(x) 
   Year  Production
0  2000           4
1  2002           6
2  2004           7
3  2006          15
4  2008          24
5  2010           2
6  2012          19
7  2014           5
8  2016          16
9  2018           4

3.The number of bed-sheets manufactured by a factory during five consecutive weeks is given below.
Week First Second Third Fourth Fifth
Number of Bed-sheets 600 850 700 300 900

Draw the bar graph representing the above data

In [10]:
import matplotlib.pyplot as plt
week=["First","Second","Third","Fourth","Fifth"]
num=[600,850,700,300,900]
plt.title("production by factory")
plt.xlabel("week")
plt.ylabel("NO of Bed Sheets")
plt.bar(week,num)
plt.show()

4.The number of students in 7 different classes is given below. Represent this data on the bar graph.
Class 6th 7th 8th 9th 10th 11th 12th
Number_of Students 130 120 135 130 150 80 75

In [13]:
import matplotlib.pyplot as plt
cl=[ "6th", "7th", "8th", "9th", "10th", "11th", "12th"]
no=[130, 120,  135,  130, 150, 80, 75]

plt.ylabel("Number_of Students")
plt.xlabel("Class")

plt.bar(cl,no)
plt.show()

5.Write a python program to draw line chart from the given financial data of ABC Co. For 5 days in the form a DataFrame namely fdf as shown below.

Day1    Day2    Day3    Day4    Day5 

0 74.25 56.03 59.30 69.00 89.65
1 76.06 68.71 72.07 78.47 79
2 69.50 62.89 77.65 65.53 80.75
3 7.55 56.42 66.46 76.85 85.08

also save the graph with the name fin.png

In [1]:
import pandas as pd
import matplotlib.pyplot as plt
data={"day1":[74.25, 76.06, 69.50,7.55],
      "day2":[56.03, 68.71, 62.89, 56.42],
      "day3":[59.30, 72.07, 77.65,66.46],
      "day4":[69.00, 78.47, 65.53, 76.85],
      "day5":[89.65, 79, 80.75, 85.08]
     }

fdf=pd.DataFrame(data)
fdf.plot()
plt.savefig("fin.png")
In [ ]:
 
Share: