Info Practical[1]
Info Practical[1]
PRACTICAL FILE
INFORMATICS PRACTICES(065)
REGISTRATION NUMBER:
SUBMITTED TO : Ms.Karthiga
BONAFIDE CERTIFICATE
This is to certify that this practical file is the bonafide work of Mr. Saad Shaukat
Shaikh of Grade XII, Section Taurus, who has satisfactorily completed the
Practical Assignments in Informatics Practices for the AISSCE as prescribed by
the CBSE during the academic year 2024-25.
Aim:
to create pandas Series object from dictionary
Software Required:
Spyder IDE
Program
import pandas as pd
data = {'a': 1, 'b': 2, 'c': 3}
series = pd.Series(data)
print(series)
Result
The following program to create pandas Series object from dictionary has
been successfully executed and obtained the output.
Output
2. Write a program in Python to create pandas Series object from
ndarray.
Aim:
to create pandas Series object from ndarray
Software Required:
Spyder IDE
Program
import pandas as pd
import numpy as np
ar = np.array([10, 20, 30])
series = pd.Series(ar)
print(series)
Result
The following program to create pandas Series object from ndarray has been
successfully executed and obtained the output.
Output
3.Write a program to perform mathematical operation on two
Pandas Series.
s1=[22,44,66,88,100] ,s2=[11,22,33,44,55].
Aim:
to perform mathematical operation on two Pandas Series
Software Required:
Spyder IDE
Program
s1 = pd.Series([22, 44, 66, 88, 100])
s2 = pd.Series([11, 22, 33, 44, 55])
print("Addition:", s1 + s2)
print("Subtraction:", s1 - s2)
print("Multiplication:", s1 * s2)
print("Division:", s1 / s2)
Result
The following program to perform mathematical operation on two Pandas
Series has been successfully executed and obtained the output.
Output
4.Write a pandas program to create a Series object Temp1 that
stores temperature of seven days in it.Now define indexes as
‘Sunday’,’Monday’….upto ‘Saturday’and print the Series again.Now
print attributes of the Series as well as average temperature of 7
days.
Aim:
to create a Series object Temp1 that stores temperature of seven days in
it,print it and find the average temperature
Software Required:
Spyder IDE
Program
temp = pd.Series([30, 32, 33, 29, 31, 28, 30], index=['Sunday', 'Monday',
'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
print("Series:\n", temp)
print("Attributes:")
print("Index:", temp.index)
print("Values:", temp.values)
print("Average temperature:", temp.mean())
Result
The following program to create a Series object Temp1 that stores
temperature of seven days in it,print it and find the average temperature has
been successfully executed and obtained the output.
Output
5. Write a Pandas program to add some data on an existing Series.
Aim:
to add some data on an existing Series
Software Required:
Spyder IDE
Program
import pandas as pd
s1 = pd.Series([1, 2, 3])
print(s1)
s2 = pd.Series([4, 5, 6])
print(s2)
s=pd.concat([s1, s2])
print(s)
Result
The following program to add some data on an existing Series has been
successfully executed and obtained the output.
Output
6.Create a Series from an array of 25 numbers.Print as per the
following queries:
S1=[21,36,37,28,38,27,33,49,12,58,58,37,34,41,39,26,50,21,19,34,3
4,41,4 8,18]
a. Print second element.
b. Print 5th element onwards.
c. Print all the elements in reverse order.
d. Print 10th to 20th elements.
e. Print 5th to last elements jumping 2 elements.
f. Print 20th to last elements by adding 5 in each element.
g. Print twice of each element.
h. Print bottom 5 elements 3,7 10,15,19,24
Aim:
to create a Series from an array of 25 numbers. Print as per the following
queries
Software Required:
Spyder IDE
Program
Lst=[21,36,37,28,38,27,33,49,12,58,58,37,34,41,39,26,50,21,19,34,34,41,4,
8,18,36]
s1=pd.Series(Lst)
line='_'*50
print("Original Series",line)
print(s1)
print(line)
print("Second Element is:",s1[1])
Output
print(line)
print("5th element onwards is\n"+line)
print(s1[4:])
print("Elements in reverse order:\n"+line)
print(s1[::-1])
print("10th to 20th elements is:\n"+line)
print(s1[9:12])
print(" 5th to last element skip by 2 elements:\n"+line)
print(s1[4:2])
print("20th to last element by adding 5 to each element is :\n",line)
print(s1[20:]+5)
print(line)
print("Twice of each element is \n"+line)
print(s1*2)
print(line)
print("Bottom 5 elements is:\n"+line)
print(s1.tail())
print(s1[3],s1[7],s1[10],s1[15],s1[19],s1[23])
Result
The following program to create a Series from an array of 25 numbers. Print
as per the following queries has been successfully executed and obtained the
output.
Output
Topic:Pandas Dataframes
1.Write a Python program to create a dataframe as given below and
display all its attributes(index, columns, shape, size, axes, rows and
columns).
Aim:
to create a dataframe as given below and display all its attributes(index,
columns, shape, size, axes, rows and columns)
Software Required:
Spyder IDE
Program
import pandas as pd
data = {'Name': ['Abdullah', 'Febin', 'Omar', 'Zahid'],
'Age': [25, 30, 35, 40],
'City': ['Jabriya', 'Abbasiya', 'Fahaheel', 'Hawally']}
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
print("\nAttributes:")
print("Index:", df.index)
print("Columns:", df.columns)
print("Shape (rows, columns):", df.shape)
print("Size (total elements):", df.size)
print("Axes:", df.axes)
print("Number of Rows:", df.shape[0])
print("Number of Columns:", df.shape[1])
Result
The following program to create a Series object Temp1 that stores
temperature of seven days in it,print it and find the average temperature has
been successfully executed and obtained the output.
Output
2.Write a Python program to create a dataframe Cricket with
columns playername, Age, TotalScore, Century, and Fifties for ten
players.(Add player_id from 101 to 110 in the dataframe during
creation.
a.Now using head() and tail() function, display top 5 rows, bottom 5
rows, last 6 rows.
b. Display details of player_id 101 using loc
c.Display rows of player_id 103,104,107 using loc.
d.Displays rows of player_id 103,104,107 using iloc.
e.Using slicing display roll number 1,3,5,7
f.Print the Transpose of the dataframe.
Aim:
to create a dataframe Cricket with columns playername, Age, TotalScore,
Century, and Fifties for ten players.(Add player_id from 101 to 110 in the
dataframe during creation
Software Required:
Spyder IDE
Program
import pandas as pd
data = {
'player_id': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
'playername': ['Dhoni', 'Sachin', 'Virat', 'Shikar', 'Rohit',
'Suresh', 'Chris', 'David', 'Gautham', 'Yuvraj'],
'Age': [36, 47, 32, 34, 33, 33, 41, 34, 39, 38],
'TotalScore': [10599, 18426, 11867, 5688, 9115, 5165, 10480, 5303, 5238,
8609],
'Century': [9, 49,43,17,29,5,25,18,11,14],
'Fifties': [73,96,58,29,43,36,54,21,34,52]
}
cricket_df = pd.DataFrame(data)
print("Cricket DataFrame:")
Output
print(cricket_df)
print("\nTop 5 rows using head():")
print(cricket_df.head())
print("\nBottom 5 rows using tail():")
print(cricket_df.tail())
print("\nLast 6 rows using tail():")
print(cricket_df.tail(6))
print("\nDetails of player_id 101:")
print(cricket_df.loc[cricket_df['player_id'] == 101])
print("\nDetails of player_id 103, 104, 107 using loc:")
print(cricket_df.loc[cricket_df['player_id'].isin([103, 104, 107])])
indices = cricket_df[cricket_df['player_id'].isin([103, 104, 107])].index
print("\nDetails of player_id 103, 104, 107 using iloc:")
print(cricket_df.iloc[indices])
print("\nDetails of player_id 101, 103, 105, 107 using slicing:")
print(cricket_df.iloc[[0, 2, 4, 6]])
print("\nTranspose of the DataFrame:")
print(cricket_df.T)
Result
The following program to create a dataframe Cricket with columns
playername, Age, TotalScore, Century, and Fifties for ten players.(Add
player_id from 101 to 110 in the dataframe during creation has been
successfully executed and obtained the output.
Output
3.Write a program to create the following DataFrame namely Aid
that stores the aid by NGOs for different states
state toys books uniform shoes
Andhra 4656 34445 100 400
Odisha 5767 45554 500 600
Bihar 7684 45848 500 688
Jharkhand 1234 56574 488 700
W.B 5766 56575 399 456
Result
The following program to create the following DataFrame namely aid that
stores the aid by NGOs for different states and perform aforementioned
activities has been successfully executed and obtained the output.
Output
4.Write a program to create the following
DataFrame showing quarterly sale year-wise,now
write Python code as per the given questions.
Yr1 Yr2 Yr3
Qtr1 3500 5500 9000
Qtr2 5600 4600 7800
Qtr3 3300 6700 7800
Qtr4 4500 8900 2200
Aim:
Result
The following program to create the following DataFrame showing
quarterly sale year-wise and writing a Python code as per the given
questions has been successfully executed and obtained the output.
Output
5. Write a python program to create two
DataFrames and perform 4 basic arithmetic
operations such as add, substract, multiply and
divide.
Aim:
to create two DataFrames and perform 4 basic arithmetic operations such as
add, substract, multiply and divide
Software Required:
Spyder IDE
Program
import pandas as pd
data1 = {
'A': [10, 20, 30],
'B': [40, 50, 60],
'C': [70, 80, 90]
}
df1 = pd.DataFrame(data1, index=['Row1', 'Row2', 'Row3'])
data2 = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}
df2 = pd.DataFrame(data2, index=['Row1', 'Row2', 'Row3'])
print("DataFrame 1:")
print(df1)
Output
print("\nDataFrame 2:")
print(df2)
add_result = df1 + df2
print("\nAddition of DataFrames:")
print(add_result)
subtract_result = df1 - df2
print("\nSubtraction of DataFrames:")
print(subtract_result)
multiply_result = df1 * df2
print("\nMultiplication of DataFrames:")
print(multiply_result)
divide_result = df1 / df2
print("\nDivision of DataFrames:")
print(divide_result)
Result
The following program to create two DataFrames and perform 4 basic
arithmetic operations such as add, substract, multiply and divide has been
successfully executed and obtained the output.
Output
i)
ii)
iii)
6.Write a program to create the following
DataFrame as per given row and columns in it.
SName English Math Physics Chemistry Info
1 Scott 78 79 87 97 94
2 Michel 75 90 57 92 97
3 Thomas 67 85 76 80 90
4 Mathews 80 90 88 80 99
5 David 87 95 78 95 100
Now peform the following by writing Python code.
i) Add a column Total showing sum of marks of all
subjects.
ii) To increase 5 marks in the ‘Total” column for all
students.
iii) Add one more column Percentage, Calculate on the
basis of ‘Total” marks
obtained out of 500.
iv) Add a new row in the above DataFrame using loc.
v),vi),vii)
df['Total'] += 5
df['Percentage'] = (df['Total'] / 500) * 100
df.loc[5] = ['Jack', 85, 88, 82, 89, 90, 0, 0] # Adding default Total and
Percentage
df.loc[5, 'Total'] = df.loc[5, ['English', 'Math', 'Physics', 'Chemistry',
'Info']].sum()
df.loc[5, 'Percentage'] = (df.loc[5, 'Total'] / 500) * 100
new_rows = pd.DataFrame({
'SName': ['Rachel', 'Monica'],
'English': [90, 92],
'Math': [85, 88],
'Physics': [78, 80],
'Chemistry': [85, 90],
'Info': [88, 92],
'Total': [0, 0], # Initialize Total
'Percentage': [0, 0] })
new_rows['Total'] = new_rows[['English', 'Math', 'Physics', 'Chemistry',
'Info']].sum(axis=1)
new_rows['Percentage'] = (new_rows['Total'] / 500) * 100
df = pd.concat([df, new_rows], ignore_index=True)
df.loc[df['SName'] == 'Thomas', 'English'] = 70
df.loc[df['SName'] == 'Thomas', 'Total'] = df.loc[df['SName'] == 'Thomas',
['English', 'Math', 'Physics', 'Chemistry', 'Info']].sum(axis=1)
df.loc[df['SName'] == 'Thomas', 'Percentage'] = (df.loc[df['SName'] ==
'Thomas', 'Total'] / 500) * 100
print("\nUpdated DataFrame:")
print(df)
Result
The following program to create the following DataFrame as per
given row and columns in has been successfully executed and obtained
the output.
Output
7.Consider the DataFrame as created below:
Aim:
to generate line graph with suitable title and labels
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
years = [2014, 2015, 2016, 2017, 2018, 2019] # X-axis values
profits = [50, 75, 100, 125, 150, 175] # Y-axis values in Rs. (Millions)
plt.figure(figsize=(8, 5))
plt.plot(years, profits, marker='o', linestyle='-', color='k', label='Profit (in Rs.
Millions)')
plt.title('Yearly Performance of the Company', fontsize=14)
plt.xlabel('Year', fontsize=12)
plt.ylabel('Profit (in Rs. Millions)', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(loc='upper left')
plt.show()
Result
The following program to generate line graph with suitable title and
label has been successfully executed and obtained the output.
Output
2.Given the following data of rainfall in different
zones in India in mm for 12 months.Create
multiple line charts in a figure to observe any
trends form Jan to Dec.
Zones Jan Feb Mar Apr May Jun Ju Aug Sep Oct Nov De
l c
Zone 14 13 13 19 16 20 15 17 19 17 15 12
A
Zone 11 16 13 11 12 17 13 20 15 16 17 13
B
Aim:
to Create multiple line charts in a figure to observe any trends
form Jan to Dec
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
zone_a_rainfall = [14, 13, 13, 19, 16, 20, 15, 17, 19, 17, 15, 12]
zone_b_rainfall = [11, 16, 13, 11, 12, 17, 13, 20, 15, 16, 17, 13]
plt.figure(figsize=(10, 6))
plt.xlabel('Months', fontsize=12)
plt.tight_layout()
plt.show()
Result
The following program to Create multiple line charts in a figure to
observe any trends form Jan to Dec has been successfully executed
and obtained the output.
Output
3.Given the school result data,analyse the performance of
the students on different parameters eg:subject wise or
class wise.
Aim:
to create line charts on students performance subject-wise and
class-wise.
Software Required:
Spyder IDE
Program
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Student': ['John', 'Emma', 'Liam', 'Olivia', 'Noah', 'Ava'],
'Class': [10, 10, 9, 9, 10, 9],
'Math': [85, 90, 75, 95, 65, 78],
'Science': [78, 82, 88, 91, 72, 85],
'English': [88, 79, 84, 89, 74, 83],
'Social Studies': [92, 85, 80, 87, 68, 80]
}
df = pd.DataFrame(data)
print("School Result Data:")
print(df)
subject_avg = df[['Math', 'Science', 'English', 'Social Studies']].mean()
print("\nSubject-wise Average Scores:")
print(subject_avg)
Output
class_avg = df.groupby('Class')[['Math', 'Science', 'English', 'Social
Studies']].mean()
print("\nClass-wise Average Scores:")
print(class_avg)
plt.figure(figsize=(8, 5))
subject_avg.plot(kind='bar', color=['red', 'blue', 'orange', 'green'],
alpha=0.7)
plt.title('Subject-wise Average Performance', fontsize=16)
plt.xlabel('Subjects', fontsize=12)
plt.ylabel('Average Scores', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
class_avg.plot(kind='bar', color=['red', 'blue', 'orange', 'green'], figsize=(10,
6), alpha=0.8)
plt.title('Class-wise Average Performance', fontsize=16)
plt.xlabel('Class', fontsize=12)
plt.ylabel('Average Scores', fontsize=12)
plt.legend(title="Subjects")
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
Result
The following program to create line charts on students performance
subject-wise and class-wise has been successfully executed and obtained
the output.
Output
4.Write a program to analyze and plot appropriate
multiple bar char with title and legend.
Aim:
to analyze and plot appropriate multiple bar chart with title and
legend
Software Required:
Spyder IDE
Program
import pandas as pd
import matplotlib.pyplot as plt
data = {'Subjects': ['Math', 'Science', 'English', 'Social Studies'], 'Class 9':
[82, 88, 85, 83],'Class 10': [80, 77, 80, 82]}
df = pd.DataFrame(data)
x = range(len(df['Subjects']))
bar_width = 0.35
plt.figure(figsize=(10, 6))
plt.bar(x, df['Class 9'], width=bar_width, label='Class 9', color='pink',
edgecolor='black')
plt.bar([p + bar_width for p in x], df['Class 10'], width=bar_width,
label='Class 10', color='grey', edgecolor='black')
plt.title('Comparison of Class Performance by Subjects', fontsize=16)
plt.xlabel('Subjects', fontsize=12)
plt.ylabel('Scores', fontsize=12)
plt.xticks([p + bar_width / 2 for p in x], df['Subjects'
plt.legend(title='Class')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
Result
The following program to analyze and plot appropriate multiple bar char
with title and legend has been successfully executed and obtained the
output.
Output
5.Consider the data given below in the
table.Create a bar chart depicting the
downloads of the app.
AppName Total Downloads
Angry Bird 197000
Teen Titan 209000
Marvel Comics 414000
Color Me 196000
Fun Run 272000
Crazy Taxi 311000
Igram Pro 213000
Wapp Pro 455000
Math Formulas 278000
Aim: To analyze and plot a bar chart
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
apps = [ "Angry Bird", "Teen Titan", "Marvel Comics", "Color Me", "Fun Run",
"Crazy Taxi", "Igram Pro", "Wapp Pro", "Math Formulas"]
downloads = [197000, 209000, 414000, 196000, 272000, 311000, 213000,
455000, 278000]
plt.figure(figsize=(12, 6))
plt.bar(apps, downloads, color='yellow', edgecolor='black')
plt.title('App Downloads Comparison', fontsize=16)
plt.xlabel('App Name', fontsize=12)
plt.ylabel('Total Downloads', fontsize=12)
plt.xticks(rotation=45, ha='right')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
Result
The following program to analyze and plot a bar chart has been
successfully executed and obtained the output.
Output
6.Given the following data of rainfall in North and South zones
of india in mm for 12 months.
Zones Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
North 14 13 13 19 16 20 15 17 19 17 15 12
South 16 20 13 20 20 17 11 16 13 14 17 20
Aim:
To analyze and plot appropriate bar graphs to differentiate between
two given datas
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
import numpy as np
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec']
north_rainfall = [14, 13, 13, 19, 16, 20, 15, 17, 19, 17, 15, 12]
south_rainfall = [16, 20, 13, 20, 20, 17, 11, 16, 13, 14, 17, 20]
x = np.arange(len(months))
width = 0.35
plt.figure(figsize=(10, 6))
plt.bar(x - width/2, north_rainfall, width, label='North Zone', color='blue')
plt.bar(x + width/2, south_rainfall, width, label='South Zone', color='black')
plt.xticks(ticks=x, labels=months)
plt.title('Monthly Rainfall (North vs. South)', fontsize=14)
plt.xlabel('Month', fontsize=12)
plt.ylabel('Rainfall (mm)', fontsize=12)
plt.legend()
plt.show()
Result
The following program to analyze and plot appropriate bar graphs to
differentiate between two given data has been successfully executed and
obtained the output.
Output
7.Write a program in Python Pandas to create the following DataFrame “df”
from a dictionary. Draw line charts to show the plotting of score1 and score2
for all batsmen. Put legends and titles. Specify different colors and line styles
of your choice for both plotted lines. Change font size of the titles to 15 and
color to green
B_No Name Score1 Score2 Location
1 M.S.Dhoni 95 80 Ranchi
2 Virat Kohli 85 92 Delhi
3 Sachin 110 75 Mumbai
4 Karthik 75 80 Delhi
Aim:
To create the following DataFrame “df” from a dictionary. draw line
charts to show the plotting of score1 and score2 for all batsmen
and put legends and titles
Software Required:
Spyder IDE
Program
import pandas as pd
import matplotlib.pyplot as plt
data = { "B_No": [1, 2, 3, 4],
"Name": ["M.S.Dhoni", "Virat Kohli", "Sachin", "Karthik"],
"Score1": [95, 85, 110, 75],
"Score2": [80, 92, 75, 80],
"Location": ["Ranchi", "Delhi", "Mumbai", "Delhi"]}
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
plt.figure(figsize=(10, 6))
plt.plot(df["Name"], df["Score1"], label="Score1", color="blue",
linestyle="--", marker="o")
plt.plot(df["Name"], df["Score2"], label="Score2", color="red", linestyle="-",
marker="x")
Output
plt.title("Scores of Batsmen", fontsize=15, color="green")
plt.xlabel("Batsmen", fontsize=12)
plt.ylabel("Scores", fontsize=12)
plt.legend()
plt.tight_layout()
plt.grid(visible=True, linestyle="--", alpha=0.6)
plt.show()
Result
The following program To create the following DataFrame “df” from a
dictionary. draw line charts to show the plotting of score1 and
score2 for all batsmen and put legends and titles has been
successfully executed and obtained the output.
Output
8.Given the ages of 50 participants in some game.
Write a program to plot a histogram from give
data with 10 bins.
Data=[10,11,13,13,15,16,17,18,19,21,23,23,23,24,24,25,
25,25,25,25,26,26,27,27,27,27,29,30,30,30,30,31,33,34,3
4,35,36,36,37,37,37,38,39,40,40,40,41,42,43,43]
Aim:
to plot a histogram from give data with 10 bins
Software Required:
Spyder IDE
Program
import matplotlib.pyplot as plt
data = [
10, 11, 13, 13, 15, 16, 17, 18, 19, 21, 23, 23, 23, 24, 24, 25, 25, 25, 25,
25,
26, 26, 27, 27, 27, 27, 29, 30, 30, 30, 30, 31, 33, 34, 34, 35, 36, 36, 37,
37,
37, 38, 39, 40, 40, 40, 41, 42, 43, 43]
plt.figure(figsize=(10, 6))
plt.hist(data, bins=10, color='orange', edgecolor='black', alpha=0.7)
plt.title('Age Distribution of Participants', fontsize=15, color='black')
plt.xlabel('Age Groups', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
Result
The following program to plot a histogram from give data with 10 bins
has been successfully executed and obtained the output.
Output
9.Given below are the sugar levels for men and
women in a city.Compare the sugar levels amongst
them.
Men=[113,84,90,150,149,88,93,115,135,80,77,82,129]
Women=[67,98,89,120,133,150,84,69,89,79,120,112,100]
Aim:
to plot a histogram from give data.
Software Required:
Spyder IDE
Program
import matplotlib.pylab as plt
sugar_men = [113,85,90,150,149,88,93,115,135,80,77,82]
sugar_women = [67,98,89,120,133,150,84,69,79,120,112,100]
Result
The following program to plot a histogram from give data has been
successfully executed and obtained the output.
Output
Topic:CSV Programs
Program
import pandas as pd
data = {
df = pd.DataFrame(data)
csv_file = "sample_data.csv"
df.to_csv(csv_file, index=False)
imported_df = pd.read_csv(csv_file)
print("Imported DataFrame:")
print(imported_df)
Result
Aim:
to create and open a DataFrame using “student_result.csv” file
using pandas,to display row labels,column labels,shape(no of rows
and columns)of the csv file.
Software Required:
Spyder IDE
Program
import pandas as pd
data = {"Name": ["John", "Alice", "Bob", "Emma"],"Math": [85, 78, 92,
88],"Science": [90, 85, 87, 95],"English": [88, 90, 85, 92]}
student_results = pd.DataFrame(data)
csv_file = "student_result.csv"
student_results.to_csv(csv_file, index=False)
print(f"DataFrame exported to '{csv_file}' successfully.\n")
imported_df = pd.read_csv(csv_file)
print("Row Labels (Index):")
print(student_results.index)
print("\nColumn Labels:")
print(student_results.columns)
print("\nShape of the DataFrame (Number of Rows and Columns):")
print(student_results.shape)
Result
The following program to create and open a DataFrame using
“student_result.csv” file using pandas,to display row labels,column
labels,shape(no of rows and columns)of the csv file has been
successfully executed and
Output
12.Read a CSV file to create a DataFrame and do the
following operations:
To display name,gender and percentage from
file.
To display the first and last 2 rows from the file.
Aim:
to create a DataFrame and do operations on it
Software Required:
Spyder IDE
Program
import pandas as pd
data = {
"Name": ["John", "Alice", "Bob", "Emma", "Mike", "Sophia"],
"Gender": ["Male", "Female", "Male", "Female", "Male", "Female"],
"Percentage": [88.0, 84.3, 88.0, 91.7, 78.3, 87.3]
}
student_results = pd.DataFrame(data)
csv_file = "student_result.csv"
student_results.to_csv(csv_file, index=False)
print(f"DataFrame exported to '{csv_file}' successfully.\n")
print("Name, Gender, and Percentage columns:")
print(student_results[["Name", "Gender", "Percentage"]])
print("\nFirst 2 rows of the DataFrame:")
print(student_results.head(2))
print("\nLast 2 rows of the DataFrame:")
print(student_results.tail(2))
Result
i)To Display names of the product, whose name starts with “C”in
ascending order of Price
ii)To display code, product name and City of the products whose
quantity is less than 100
iv)To insert a new row in the table 110, ‘Pizza’, ‘Papa Jones’,
120, ‘Kolkata’, 50.00
v)SELECT Pname FROM SHOPEE WHERE Pname IN(“Jam”,”Coffee”);
i)To list the Names of those students, who have obtained Division as
FIRST in ascending order of Name.
(iv) Display names of each department along with total salary being
given to doctors of that department.