Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views21 pages

Informatic Practices HHW

The document contains a series of Python programming exercises focused on using the pandas library for data manipulation and matplotlib for data visualization. It includes tasks such as correcting code errors, creating dataframes, plotting charts, and understanding aggregate functions. Additionally, it covers SQL commands for handling decimal numbers and generating random data for analysis.
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)
16 views21 pages

Informatic Practices HHW

The document contains a series of Python programming exercises focused on using the pandas library for data manipulation and matplotlib for data visualization. It includes tasks such as correcting code errors, creating dataframes, plotting charts, and understanding aggregate functions. Additionally, it covers SQL commands for handling decimal numbers and generating random data for analysis.
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/ 21

IP HOLIDAY HOMEWORK

1) The python code written below has syntactical errors. Rewrite the correct code and
underline the corrections made.

Import pandas as pd

df={"Technology":["Programming","Robotics","3DPrinting"],"Time(in months)":[4,4,3]}

df= Pd.dataframe(df)

Print(df)

ANSWER

Import pandas as pd

df={"Technology":["Programming","Robotics","3DPrinting"],"Time(in months)":[4,4,3]}

df = pd.DataFrame(df)

Print(df)
2. Complete the given Python code to get the required output as: Rajasthan

import _______as pd

di = {'Corbett': 'Uttarakhand', 'Sariska': 'Rajasthan', 'Kanha': 'Madhya


Pradesh’,'Gir':'Gujarat'}

NP =_____ . Series( ______)

print(NP[ ___________])

ANSWER

import pandas as pd

di = {'Corbett': 'Uttarakhand', 'Sariska': 'Rajasthan', 'Kanha': 'Madhya Pradesh',


'Gir':'Gujarat'}

NP = pd.Series(di)

print(NP['Sariska'])
3)

import pandas as pd

rollno=[1,2,3,4,5,6,7]

_____=pd.Series(rollno) #Statement 1

print (p.head(__________ )) #Statement 2

ANSWER

import pandas as pd

rollno = [1,2,3,4,5,6,7]

p = pd.Series(rollno) # Statement 1

print(p.head()) # Statement 2

OUTPUT

0 1

1 2

2 3

3 4

4 5

5 6

6 7

dtype: int64
4) 4. Consider two objects L and S. L is a list whereas S is a Series. Both have values 20,
40,90, 110. What will be the output of the following two statements considering that the
above objects have been created already.

print (L+2) #Statement 1

print (S+2) #Statement 2

ANSWER

Statement 1: print(L+2)

Since L is a list, the + operator is not defined for lists and integers. You will get a
TypeError:

>> TypeError: can only concatenate list (not "int") to list

This is because lists in Python do not support element-wise operations like addition with a
scalar value.

Statement 2: print(S+2)

Since S is a Pandas Series, the + operator is overloaded to perform element-wise addition.


The output will be:

0 22

1 42

2 92

3 112

dtype: int64

This is because the + operator is applied element-wise to each value in the Series, adding 2
to each value.
5. Mr. Harry wants to draw a line chart using a list of elements named LIST. Complete the
code to perform the following operations:

a. To plot a line chart using the given LIST

b. To give a y-axis label to the line chart named "sample number".

import matplotlib.pyplot as PLINE

LIST=[10,20,30,40,50,60]

#Statement 1

#Statement 2

ANSWER

import matplotlib.pyplot as plt

LIST = [10, 20, 30, 40, 50, 60]

# Statement 1: Plot a line chart using the given LIST

plt.plot(LIST)

# Statement 2: Give a y-axis label to the line chart named "sample number"

plt.ylabel("sample number")

# Add a title to the chart (optional)


plt.title("Line Chart Example")

# Show the plot

plt.show()
6. A dictionary ‘stationary’ contains the following:

stationary={‘Name’:[ ‘books’, ‘copies’, ‘pencil box’, ‘Pen’],

‘Price’:[ 500,350, 400,250]

ANSWER

print(stationary['Name'])

['books', 'copies', 'pencil box', 'Pen']

print(stationary['Price'])

[500, 350, 400, 250]

new_dict = dict(zip(stationary['Name'], stationary['Price']))

print(new_dict)

{'books': 500, 'copies': 350, 'pencil box': 400, 'Pen': 250}


7. Write statements for the following:

a. Create a Dataframe named “stock”

b. Add a column called ‘discount’ with the following data: [ 15, 20, 30, 25]

c. Delete column discount with all values.

ANSWER

import pandas as pd

# a. Create a Dataframe named “stock”

stock = pd.DataFrame({

'Name': ['books', 'copies', 'pencil box', 'Pen'],

'Price': [500, 350, 400, 250]

})

# b. Add a column called ‘discount’ with the following data: [ 15, 20, 30, 25]

stock['discount'] = [15, 20, 30, 25]

# c. Delete column discount with all values

stock = stock.drop('discount', axis=1)


8. Differentiate between Single Row and Multi Row Functions?

ANSWER

The main difference between single row and multiple row functions is that single row
functions work on one row at a time and returns one result for every row. While multiple
row functions work on a group of rows and return one result for every group
9. Write a program to create the series that stores the term marks of 10 students. Find the
highest and lowest three marks scored by students.

ANSWER

import pandas as pd

# Create a Series to store the term marks of 10 students

marks = pd.Series([85, 92, 78, 95, 88, 76, 91, 89, 90, 82])

# Print the original Series

print("Original Series:")

print(marks)

# Find the highest three marks

highest_three = marks.nlargest(3)

print("\nHighest three marks:")

print(highest_three)

# Find the lowest three marks

lowest_three = marks.nsmallest(3)

print("\nLowest three marks:")

print(lowest_three)

OUTPUT
10. Write a program to create a series from list marks and taking index values from list roll
no. Show all elements that are above 80 marks.

ANSWER

import pandas as pd

# Create a list of marks

marks = [85, 92, 78, 95, 88, 76, 91, 89, 90, 82]

# Create a list of roll numbers

roll_no = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Create a Series from the list of marks and roll numbers

series = pd.Series(marks, index=roll_no)

# Print the original Series

print("Original Series:")

print(series)

# Show all elements that are above 80 marks

print("\nElements above 80 marks:")

print(series[series > 80])

88
9

OUTPUT
11. What is the difference between the following two statements, which are creating two
dataframes using the same dataframe (Pandas library has been imported as pd)?

i. Df2=pd.DataFrame(df1) ii. Df3=pd.DataFrame(df1, copy=True)

ANSWER

The difference between the two statements lies in how they handle the data when creating
a new DataFrame.

i. Df2=pd.DataFrame(df1)

When you create a new DataFrame Df2 from an existing DataFrame df1 without specifying
the copy parameter, it creates a new DataFrame object but shares the same data as df1.
This means that both Df2 and df1 point to the same data in memory. Any changes made to
Df2 will also affect df1, and vice versa.

ii. Df3=pd.DataFrame(df1, copy=True)

When you create a new DataFrame Df3 from an existing DataFrame df1 with the
copy=True parameter, it creates a new DataFrame object and copies the data from df1 to
Df3. This means that Df3 has its own separate data in memory, independent of df1. Any
changes made to Df3 will not affect df1, and vice versa
ANSWER

# i) For book and uniform only

print(aid[['Books', 'Uniform']])

# ii)For shoes only

print(aid['Shoes'])
13. What are aggregate functions? How are they useful?

ANSWER

An aggregate function performs a calculation on a set of values, and returns a single value.
Except for COUNT(*) , aggregate functions ignore null values. Aggregate functions are often
used with the GROUP BY clause of the SELECT statement. All aggregate functions are
deterministic

14. What is the use of GROUP BY clause> Give example.

ANSWER

The GROUP BY clause causes the rows of the items table to be collected into groups, each
group composed of rows that have identical order_num values (that is, the items of each
order are grouped together). After the database server forms the groups, the aggregate
functions COUNT and SUM are applied within each group.
15. WAP to plot a line chart between two given arrays

A=[4,56,78,23,45,67,89]

B=[0,1,2,3,4,5,6]

ANSWER

import matplotlib.pyplot as plt

A = [4, 56, 78, 23, 45, 67, 89]

B = [0, 1, 2, 3, 4, 5, 6]

plt.plot(B, A)

plt.xlabel('Index')

plt.ylabel('Value')

plt.title('Line Chart')

plt.show()
ANSWER

import pandas as pd

df1 = pd.DataFrame([

['Arjun', 'XII', 95],

['Ruchi', 'X', 84],

['Prerna', 'XI', 90],

['Himali', 'XI', 75]

], columns=['Name', 'Class', 'Marks'])

print(df1)
ANSWER

import pandas as pd

D1 = pd.Series({

'TEST 1': 30,

'TEST 2': 40,

'TEST 3': 50,

'TEST 4': 100

}, name='MAX MARKS')

print(D1)

18. Consider the decimal number x with value 54567.8577. Write commands in SQL to: i.
display the whole number without round it off. ii.round it to 2 places of the decimal.

ANSWER

SELECT FLOOR(54567.8577) AS WholeNumber;


SELECT ROUND(54567.8577, 2) AS RoundedNumber;

19. A company randomly generated a weekly winning number (between 0. 1000) for 10
weeks. An employee of the company wants to plot the sine values of winningnumbers
(nump.sin( ) function) on a line chart. Write a program to help him accomplish this.

ANSWER

import numpy as np

import matplotlib.pyplot as plt

# Generate 10 random winning numbers between 0 and 1000

winning_numbers = np.random.uniform(0, 1000, 10)

# Calculate the sine values of the winning numbers

sine_values = np.sin(winning_numbers)

# Create a line chart of the sine values

plt.plot(sine_values)

plt.xlabel('Week')

plt.ylabel('Sine Value')

plt.title('Sine Values of Winning Numbers')

plt.show()
20. Write a small python code to create a dataframe with headings (a and b) from the list
given below: [ [1,2],[3,4],[5,6],[7,8] ]

ANSWER

import pandas as pd

data = [[1,2],[3,4],[5,6],[7,8]]

df = pd.DataFrame(data, columns=['a', 'b'])

print(df)

OUTPUT

You might also like