Pandas DataFrames: Exercises


2. Modifying a Pandas DataFrame. In Pandas, you can modify a DataFrame by changing, adding, or removing rows and columns. To change a value, use indexing and assignment. To add rows or columns, you can use methods like loc[] and assign(). To remove rows or columns, you can use methods like drop().

For example, you can change the age of a student like this: df.loc[1, 'Age'] = 23.


# Import the Pandas library import pandas as pd # Create a Pandas DataFrame with student information df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [20, 22, 21]}) # Modify the age of the second student df.loc[1, ___] = 23 # Add a new student's information df = df.append(pd.Series({'Name': 'David', 'Age': 19}), ignore_index=True) # Remove the first student from the DataFrame df = df.___ # Print the modified DataFrame print(df) # Import the Pandas library import pandas as pd # Create a Pandas DataFrame with student information df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [20, 22, 21]}) # Modify the age of the second student df.loc[1, 'Age'] = 23 # Add a new student's information df = df.append(pd.Series({'Name': 'David', 'Age': 19}), ignore_index=True) # Remove the first student from the DataFrame df = df.drop(0) # Print the modified DataFrame print(df) test_object("df") success_msg("You have correctly modified the Pandas DataFrame.")
To modify a Pandas DataFrame, use indexing for changes, and Pandas methods like append() and drop() for additions and removals.

Previous Exercise Next Exercise