Pandas DataFrames: Exercises


4. Grouping and Aggregating Data. In Pandas, you can group rows of a DataFrame by one or more columns and perform aggregate operations on the groups. You can use the groupby() function and aggregation functions like sum(), mean(), and count().

For example, you can group students by age and calculate the average age of each group like this: df.groupby('Age')['Age'].mean().


# 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]}) # Group students by age and calculate the average age of each group grouped_df = df.groupby(___)['Age'].mean() # Print the grouped DataFrame print(grouped_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]}) # Group students by age and calculate the average age of each group grouped_df = df.groupby('Age')['Age'].mean() # Print the grouped DataFrame print(grouped_df) test_object("grouped_df") success_msg("You have correctly grouped and aggregated the data.")
To group and aggregate data in a Pandas DataFrame, use the groupby() function and aggregation functions.

Previous Exercise Next Exercise