0% found this document useful (0 votes)
34 views25 pages

Mohammad Rehan Commerce 3.0

rand

Uploaded by

rehangaming275
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views25 pages

Mohammad Rehan Commerce 3.0

rand

Uploaded by

rehangaming275
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

1

Acknowledgement……..

I would like to express my sincere gratitude to Mr


Neeraj Sir for his invaluable guidance and support
throughout the completion of this project. Their
expertise and encouragement have been
instrumental in shaping my understanding of the
subject matter.
I am also thankful to Mr Naveen Katwaal Sir for
providing the necessary resources and
environment conducive to learning, which enabled
me to undertake this project.
Additionally, I extend my appreciation to my
classmates and friends for their assistance and
cooperation during the course of this project.
Their insights and feedback have greatly
contributed to its overall quality.
Finally, I would like to acknowledge the support
of my family for their patience and understanding
during this endeavor.
Thank you all for your support, guidance and
contributions to this project.
3

CERTIFICATE….

I, ‘Mohammad Rehan’, a student of Class 12, hereby express my heartfelt gratitude to “Delhi Public
School”, for providing me the opportunity to work on the project during the academic year 2024

I would like to sincerely thank Mr Neeraj Sir for their valuable guidance, support, and

encouragement throughout the project. Their constructive feedback and expertise

helped me enhance my understanding and achieve the objectives of this project.

I am also grateful to my school, principal, and classmates for their constant motivation

and cooperation during the process. This project has been a significant learning

experience, enabling me to grow academically and personally.

---

Date: 21/11/24
(Mohammad Rehan)
4

5
6-23
24
25
5
6

Q1)….Write a program to create a


series to print scalar value “5”
four times..

# Assign the scalar value


scalar_value = 5

# Loop to print the scalar value 4 times


for _ in range(4):
print(scalar_value)

Explanation:
1. scalar_value = 5: The scalar value 5 is stored in
a variable.
2. for _ in range(4): This loop will iterate 4 times.
The underscore (_) is commonly used when the
loop variable is not needed.
3. print(scalar_value): In each iteration, the
scalar value (5) is printed.
Output:
5
5
5
5
7

Q2)….. Write a program to create a series object F1


using a dictionary that stores the number of
furniture in each lab of your school. Note: Assume
four furniture names are Table, Sofa, Chair and
stool having 40, 2,45,26 items respectively and
pandas library has been imported as pd.
import pandas as pd

# Create a dictionary with furniture names as keys and their


respective quantities as values
furniture_data = {
'Table': 40,
'Sofa': 2,
'Chair': 45,
'Stool': 26
}

# Create a Series object from the dictionary


F1 = pd.Series(furniture_data)

# Print the Series


print(F1)
Explanation:
1. Dictionary furniture_data: The dictionary stores the names of
furniture as keys and the number of items as corresponding
values.
2. pd.Series(furniture_data): This converts the dictionary into a
pandas Series object. Each key-value pair in the dictionary
becomes an index-value pair in the Series.
3. print(F1): The series object F1 is printed to show the result.

Output:
Table 40
8

Sofa 2
Chair 45
Stool 26
dtype: int64

1. Q3)….Write a program to create a series object using a


dictionary that stores the number of students in each house
of CLASS 12D of your school. Note: Assume four house
names are Beas, Chenab, Ravi and Satluj having 18, 2, 20, 18
students respectively and pandas library has been imported
as pd.
2.
import pandas as pd

# Create a dictionary with house names as keys and the number of students as values

house_data = {

'Beas': 18,

'Chenab': 2,

'Ravi': 20,

'Satluj': 18

# Create a Series object from the dictionary

students_series = pd.Series(house_data)

# Print the Series

print(students_series)

Explanation:

1. Dictionary house_data: The dictionary contains house names as keys and the
number of students in each house as values.

2. pd.Series(house_data): This converts the dictionary into a pandas Series object


where the house names become the indices and the corresponding values are
the number of students in each house.

3. print(students_series): This displays the Series object, showing the house


names and the respective number of students.

Output:
9

Beas 18

Chenab 2

Ravi 20

Satluj 18

dtype: int64

Q4)…. Write the output of the given command: import pandas as pd


s=pd.Series([1,2,3,4,5,6],index=['A','B','C','D','E','F']) print(s[s%2==0)

import pandas as pd

s = pd.Series([1, 2, 3, 4, 5, 6], index=['A', 'B', 'C', 'D', 'E', 'F'])

print(s[s % 2 == 0])

Explanation:

1. pd.Series creates a pandas Series with the given data [1, 2, 3, 4, 5, 6] and the
specified indices ['A', 'B', 'C', 'D', 'E', 'F'].

2. s % 2 == 0 computes a boolean mask where each element of the Series is


checked for divisibility by 2 (i.e., even numbers).

3. s[s % 2 == 0] filters the Series using this mask, retaining only the even values.

Output:

The output will be:

css

Copy code

B 2

D 4

F 6

dtype: int64

Q 6) Give the output: import pandas as pd


name=[‘Raj’,’Ankur’,’Harsh’]
p=pd.Series(name,index=[2,5,6]) print(p)
p1=p.reindex([2,5]) print (p1) .
10

import pandas as pd

name = ['Raj', 'Ankur', 'Harsh']

p = pd.Series(name, index=[2, 5, 6])

print(p)

p1 = p.reindex([2, 5])

print(p1)

The first print(p) prints the full p series, which is created with
the names ['Raj', 'Ankur', 'Harsh'] and the indices [2, 5, 6].
Thus, it displays:

2 Raj
5 Ankur
6 Harsh
dtype: object

The second print(p1) prints the result of p.reindex([2,


5]). Since both indices 2 and 5 exist in the original series
p, it returns a new series with only those two values
2 Raj
5 Ankur
dtype: object
The reindex method selects only the indices 2 and 5,
and because those indices are present in the original
series, no NaN values are added.
11

Q 7)How many elements will be there in the


series named “S1”? >>> S1 =
pd.Series(range(5,10)) >>> print(S1)
The series S1 is created using
pd.Series(range(5, 10)). The range(5, 10)
generates the numbers 5, 6, 7, 8, 9. This
means there are 5 elements in the series.
The output of print(S1) will be:

0 5
1 6
2 7
3 8
4 9
dtype: int64
Thus, S1 contains 5 elements.

Q 8) Consider the given DataFrame ‘Stock’: Name Price 0 Nancy Drew


150 1 Hardy boys 180 2 Diary of a wimpy kid 225 3 Harry Potter 500 Write
suitable Python statements for the following: i. Add a column called
Special_Price with the following data: [135,150,200,440]. ii. Add a new
book named ‘The Secret' having price 800. iii. Remove the column Price.
iv.Remove first and third rows from DataFrame .
12

1. Create the DataFrame Stock

First, create the initial DataFrame:

python

Copy code

import pandas as pd

# Creating the initial DataFrame

Stock = pd.DataFrame({

'Name': ['Nancy Drew', 'Hardy boys', 'Diary of a wimpy kid', 'Harry Potter'],

'Price': [150, 180, 225, 500]

})

i. Add a column Special_Price with data [135, 150, 200, 440]

python

Copy code

Stock['Special_Price'] = [135, 150, 200, 440]

ii. Add a new book named ‘The Secret’ with price 800

python

Copy code

Stock = pd.concat([Stock, pd.DataFrame({'Name': ['The Secret'], 'Price': [800], 'Special_Price':


[None]})], ignore_index=True)

iii. Remove the column Price

python

Copy code

Stock = Stock.drop(columns=['Price'])

iv. Remove the first and third rows from the DataFrame

python

Copy code

Stock = Stock.drop(index=[0, 2]).reset_index(drop=True)

Final Code

Combining everything:

python

Copy code

import pandas as pd
13

# Initial DataFrame

Stock = pd.DataFrame({

'Name': ['Nancy Drew', 'Hardy boys', 'Diary of a wimpy kid', 'Harry Potter'],

'Price': [150, 180, 225, 500]

})

# i. Add a column Special_Price

Stock['Special_Price'] = [135, 150, 200, 440]

# ii. Add a new book 'The Secret' with price 800

Stock = pd.concat([Stock, pd.DataFrame({'Name': ['The Secret'], 'Price': [800], 'Special_Price':


[None]})], ignore_index=True)

# iii. Remove the column Price

Stock = Stock.drop(columns=['Price'])

# iv. Remove the first and third rows

Stock = Stock.drop(index=[0, 2]).reset_index(drop=True)

print(Stock)

Final Output

After executing all steps, the resulting DataFrame will look like this:

markdown

Copy code

Name Special_Price

0 Hardy boys 150.0

1 Harry Potter 440.0

2 The Secret NaN

Q9) Consider the following dataframe ndf as shown below: (A) Write statements to do the
following: (a) Extract column col3 (b) Extract row t3 (c) Extract row t2’s column col2’s value (d)
Extract row t4’s columns col2, col3, and Res (e) Delete rows t2 and t3 (f) Delete columns col2 and
Res.
14

import pandas as pd

# Define a sample DataFrame

ndf = pd.DataFrame({

'col1': [10, 20, 30, 40],

'col2': [15, 25, 35, 45],

'col3': [20, 30, 40, 50],

'Res': [1, 0, 1, 0]

}, index=['t1', 't2', 't3', 't4'])

The DataFrame ndf looks like this:

markdown

Copy code

col1 col2 col3 Res

t1 10 15 20 1

t2 20 25 30 0

t3 30 35 40 1

t4 40 45 50 0

(a) Extract column col3

python

Copy code

col3 = ndf['col3']

print(col3)

Output:

yaml

Copy code

t1 20

t2 30

t3 40

t4 50

Name: col3, dtype: int64

(b) Extract row t3


15

python

Copy code

row_t3 = ndf.loc['t3']

print(row_t3)

Output:

col1 30

col2 35

col3 40

Res 1

Name: t3, dtype: int64

(c) Extract row t2's column col2's value

python

t2_col2_value = ndf.loc['t2', 'col2']

print(t2_col2_value)

Output:

Copy code

25

(d) Extract row t4’s columns col2, col3, and Res

python

t4_selected_columns = ndf.loc['t4', ['col2', 'col3', 'Res']]

print(t4_selected_columns)

Output:

col2 45

col3 50

Res 0

Name: t4, dtype: int64

(e) Delete rows t2 and t3

python

ndf_dropped_rows = ndf.drop(index=['t2', 't3'])

print(ndf_dropped_rows)

Output:
16

markdown

col1 col2 col3 Res

t1 10 15 20 1

t4 40 45 50 0

(f) Delete columns col2 and Res

python

Copy code

ndf_dropped_columns = ndf.drop(columns=['col2', 'Res'])

print(ndf_dropped_columns)

Output:

markdown

Copy code

col1 col3

t1 10 20

t2 20 30

t3 30 40

t4 40 50

Q9) (B) What will be the output produced by the following


statements? (a) print(df.at[‘t3’, ‘Res’], df.at[‘t1’, ‘col3’])
(b) print(df.iat[3,2], df.iat[2,3]) (c) print(df.loc[‘t2’ : , : ])
(d) print(df.loc[ : , ‘col3’ : ] ) (e) print(print(df.loc[‘t2’ :
‘t3’, ‘col3’ : ] ) (f) print(df.iloc[ :2, 2:] ) (g) print(df.iloc[2: ,
:3] ) (h) print(df.iloc[1:3, 2:3])
import pandas as pd

# Sample DataFrame

data = {

'col1': [10, 20, 30, 40],

'col2': [50, 60, 70, 80],

'col3': [90, 100, 110, 120],

'Res': ['A', 'B', 'C', 'D']

}
17

df = pd.DataFrame(data, index=['t1', 't2', 't3', 't4'])

The DataFrame df looks like this:

col1 col2 col3 Res

t1 10 50 90 A

t2 20 60 100 B

t3 30 70 110 C

t4 40 80 120 D

Evaluating Statements

1. (a) print(df.at['t3', 'Res'], df.at['t1', 'col3'])

o df.at['t3', 'Res'] fetches the value 'C' (row t3, column Res).

o df.at['t1', 'col3'] fetches the value 90 (row t1, column col3).

o Output: C 90

2. (b) print(df.iat[3, 2], df.iat[2, 3])

o df.iat[3, 2] fetches the value 120 (row index 3, column index 2).

o df.iat[2, 3] fetches the value 'C' (row index 2, column index 3).

o Output: 120 C

3. (c) print(df.loc['t2':, :])

o Selects all rows starting from 't2' and all columns.

o Output:

mathematica

Copy code

col1 col2 col3 Res

t2 20 60 100 B

t3 30 70 110 C

t4 40 80 120 D

4. (d) print(df.loc[:, 'col3':])

o Selects all rows and columns from 'col3' onwards.

o Output:

css

Copy code

col3 Res

t1 90 A

t2 100 B
18

t3 110 C

t4 120 D

5. (e) print(df.loc['t2':'t3', 'col3':])

o Selects rows 't2' to 't3' (inclusive) and columns from 'col3' onwards.

o Output:

css

Copy code

col3 Res

t2 100 B

t3 110 C

6. (f) print(df.iloc[:2, 2:])

o Selects the first two rows (:2) and columns starting from the 3rd column (2:).

o Output:

css

Copy code

col3 Res

t1 90 A

t2 100 B

7. (g) print(df.iloc[2:, :3])

o Selects rows starting from the 3rd row (2:) and the first three columns (:3).

o Output:

markdown

col1 col2 col3

t3 30 70 110

t4 40 80 120

8. (h) print(df.iloc[1:3, 2:3])

o Selects rows from index 1 to 2 (not including 3) and the 3rd column only
(2:3).

o Output:
markdown

Copy code

col3

t2 100

t3 110
19

Q10) What will be the output of the following code:


import pandas as pd d = {‘one’ : pd.series([1., 2., 3.], index
= [‘a’, ‘b’, ‘c’]), ‘two’ : pd.series([1., 2., 3., 4.], index = [‘a’, ‘b’ ,
‘c’, ‘d’ ]) } df . pd.dataframe(d) df1 = pd.dataframe(d,
index = [‘d’, ‘b’, ‘a’]) df2= pd.dataframe(d, index = [‘d’, ‘a’],
columns =[‘two’,‘three’]) print(df) print(df1)

import pandas as pd

# Define a dictionary of Series

d={

'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),

'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])

# Create a DataFrame from the dictionary

df = pd.DataFrame(d)

# Create DataFrame df1 with a custom index

df1 = pd.DataFrame(d, index=['d', 'b', 'a'])

# Create DataFrame df2 with a custom index and columns

df2 = pd.DataFrame(d, index=['d', 'a'], columns=['two', 'three'])

# Print the DataFrames

print(df)

print(df1)

Explanation and Output:

1. df

df is created from the dictionary d. The DataFrame will align the indices (a, b, c, d) across
the Series in the dictionary, filling missing values with NaN.

Output of df:
20

css

Copy code

one two

a 1.0 1.0

b 2.0 2.0

c 3.0 3.0

d NaN 4.0

2. df1

df1 is created with a custom index ['d', 'b', 'a']. The rows are reordered based on this index.
If any index from the new list is not present in the original data, it will be filled with NaN.

Output of df1:

css

Copy code

one two

d NaN 4.0

b 2.0 2.0

a 1.0 1.0

3. df2

df2 is created with a custom index ['d', 'a'] and columns ['two', 'three'].

• The column 'two' exists in the original data, so it is included.

• The column 'three' does not exist in the original data, so it will be filled with NaN.

Output of df2:

Copy code

two three

d 4.0 NaN

a 1.0 NaN

Final Outputs:

print(df):

css

Copy code

one two

a 1.0 1.0
21

b 2.0 2.0

c 3.0 3.0

d NaN 4.0

print(df1):

css

Copy code

one two

d NaN 4.0

b 2.0 2.0

a 1.0 1.0

Q11) Write code to do the following: Plot the following data on line
chart: Runs in Overs 10 20 MI 110 224 RCB 85
210

import matplotlib.pyplot as plt

# Data

overs = [10, 20]

mi_runs = [110, 224]

rcb_runs = [85, 210]

# Plot the data

plt.figure(figsize=(8, 6))

plt.plot(overs, mi_runs, marker='o', label='MI', color='blue')

plt.plot(overs, rcb_runs, marker='o', label='RCB', color='red')

# Add labels and title

plt.title("Runs Scored in Overs", fontsize=14)

plt.xlabel("Overs", fontsize=12)

plt.ylabel("Runs", fontsize=12)
22

# Add grid, legend, and show the plot

plt.grid(True, linestyle='--', alpha=0.6)

plt.legend(title="Teams", fontsize=10)

plt.xticks(overs)

plt.show()

Explanation:

1. Data Preparation:

o The overs are [10, 20].

o Runs scored by MI and RCB in these overs are [110, 224] and [85, 210],
respectively.

2. Plotting:

o plt.plot() is used to plot the lines for MI and RCB.

o Different colors and markers distinguish the two teams.

3. Customization:

o Titles, axis labels, and grid lines enhance readability.

o A legend indicates which line corresponds to which team.

Output:

The resulting line chart will show two lines, one for MI and one for RCB, plotting their runs
against overs.

The command given is:


python
print(animal[::-3])
23

Explanation:
• [::-3] is a slicing operation with a step of -3, which means:
o Start from the end of the series.
o Traverse the series backward, taking every third element.
When applying this step to the animal series:
1. Start from the last element (W: Wolf).
2. Move backward by three steps: T: Tiger.
3. Continue: No further valid elements (end of the series).
Output:
The result of animal[::-3] is:
W Wolf

T Tiger
dtype: object
24
25

You might also like