ByteBoard Notes Notes

Add, rename and delete rows and columns of a DataFrame

Informatics Practices XII · Experiment 10 of 38 · Pandas

12-IPPandas programs
Expt. No.10
Page No.20

Add, rename and delete rows and columns

Aim

To write a Python program that adds a column and a row to a DataFrame, renames a column and a row label, and deletes a column and a row.

Concepts used

Algorithm

  1. Create a DataFrame of names and marks with index S1–S3.
  2. Add a column Grade; add a row S4 with loc.
  3. Rename the column Marks to Score and the row S1 to R1 with rename().
  4. Delete the Grade column (axis=1) and the row S2 (axis=0) with drop().
  5. Display the DataFrame after each step.

Program

# Add, rename and delete rows and columns import pandas as pd df = pd.DataFrame({"Name": ["Asha", "Rohan", "Ira"], "Marks": [82, 67, 88]},                  index=["S1", "S2", "S3"])df["Grade"] = ["B", "C", "B"]df.loc["S4"] = ["Kabir", 91, "A"]print("After adding a column and a row:")print(df) df = df.rename(columns={"Marks": "Score"}, index={"S1": "R1"})print("After renaming:")print(df) df = df.drop("Grade", axis=1)df = df.drop("S2", axis=0)print("After deleting the Grade column and row S2:")print(df)

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python dataframe_add_rename_delete.py
After adding a column and a row: Name Marks Grade S1 Asha 82 B S2 Rohan 67 C S3 Ira 88 B S4 Kabir 91 A After renaming: Name Score Grade R1 Asha 82 B S2 Rohan 67 C S3 Ira 88 B S4 Kabir 91 A After deleting the Grade column and row S2: Name Score R1 Asha 82 S3 Ira 88 S4 Kabir 91

✓ Printed by running this program, not typed by hand.

Result

A Grade column and a row S4 (Kabir) were added. rename() changed Marks to Score and S1 to R1. drop() removed the Grade column and Rohan's row, leaving 3 rows and 2 columns.

Viva voce: what the examiner may ask

01How do you add a new column?

Assign a list of values to a new column name: df["Grade"] = [...].

02What does axis=1 mean in drop()?

Delete a column; axis=0 (the default) deletes a row.

03Does rename() change the DataFrame itself?

No. It returns a new DataFrame, which is why it is assigned back to df.

Variations for the lab test

  1. Delete a column using del df["Name"].
  2. Add a column whose values are Marks + 5.
  3. Rename two columns in one rename() call.
! Common mistake Calling df.drop("Grade") without axis=1 looks for a row named Grade and raises KeyError.
Back to the 12-IP index