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.

Pandas operations

import pandas as pd

# Create DataFrame
data = {
    'Maths': [100, 95, 85],
    'Science': [100.0, 50.0, 90.0],
    'SST': [60.0, 57.48, 53.58]
}
df = pd.DataFrame(data, index=['Amit', 'Mohan', 'Sudha'])
print("Initial DataFrame:\n", df)

# (i) Add new column "Total"
df['Total'] = df['Maths'] + df['Science'] + df['SST']

# (ii) Add new 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) Print only Score of Maths and Science
print(df[['Maths', 'Science']])

# (iv) Update Science of Sudha to 85.0
df.at['Sudha', 'Science'] = 85.0

# (v) Delete row 'Mohan'
df = df.drop('Mohan')

print("Final DataFrame:\n", df)

✅ Explanation of outputs:

  • (i) Adds Total column.

  • (ii) Row T5 = [75.6, 98.6, 56.0, 230.2].

  • (iii) Prints just Maths & Science columns.

  • (iv) Sudha’s Science score becomes 85.0.

  • (v) Mohan’s row removed.

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.