Write the code to create a DataFrame ‘df’ and answer the questions followed.

SOLUTION

Write the code to create a DataFrame ‘df’ and answer the questions followed.

import pandas as pd
import numpy as np

# Original DataFrame
data = {
    "Col1": [100.0, 95.8, np.nan, 85.0],
    "Col2": [100.0, 100.0, 100.0, 85.0],
    "Col3": [60.0, 57.48, 53.58, np.nan]
}
index = ["T1", "T2", "T3", "T4"]
df = pd.DataFrame(data, index=index)

print("Original DataFrame:")
print(df)

# i) Add one column Total = Col1 + Col2 + Col3
df["Total"] = df["Col1"] + df["Col2"] + df["Col3"]

# ii) Add one row T5 with values 75.6, 98.6, 56.0
df.loc["T5"] = [75.6, 98.6, 56.0, 75.6+98.6+56.0]

# iii) Change column names
df.rename(columns={"Col1": "Maths", "Col2": "Science", "Col3": "SST"}, inplace=True)

# iv) Print score of Maths and Science only
print("\nScores of Maths and Science:")
print(df[["Maths", "Science"]])

# v) Update value of T3 Row and Col1 (NaN -> 85.0)
df.at["T3", "Maths"] = 85.0

print("\nFinal DataFrame after all changes:")
print(df)

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.