Pandas DataFrames: Exercises


5. Merging Pandas DataFrames. In Pandas, you can merge two or more DataFrames based on common columns or keys. You can use the merge() function to combine DataFrames into a single DataFrame.

For example, you can merge two DataFrames with student information and course enrollment data like this: merged_df = pd.merge(students_df, courses_df, on='StudentID').


# Import the Pandas library import pandas as pd # Create two Pandas DataFrames with student and course information students_df = pd.DataFrame({'StudentID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']}) courses_df = pd.DataFrame({'StudentID': [2, 3, 4], 'Course': ['Math', 'Science', 'History']}) # Merge the DataFrames based on StudentID merged_df = ___ # Print the merged DataFrame print(merged_df) # Import the Pandas library import pandas as pd # Create two Pandas DataFrames with student and course information students_df = pd.DataFrame({'StudentID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']}) courses_df = pd.DataFrame({'StudentID': [2, 3, 4], 'Course': ['Math', 'Science', 'History']}) # Merge the DataFrames based on StudentID merged_df = pd.merge(students_df, courses_df, on='StudentID') # Print the merged DataFrame print(merged_df) test_object("merged_df") success_msg("You have correctly merged Pandas DataFrames based on StudentID.")
To merge Pandas DataFrames, use the merge() function and specify the common column or key.

Previous Exercise Next Exercise