10 exercices in pandas with solutions
- User
10 exercices in pandas with solutions
- Assistant
Here are 10 pandas exercises along with their solutions. These exercises will help you build a strong understanding of the pandas library, which is widely used for data manipulation and analysis in Python.
Exercise 1:
Import pandas and create a DataFrame with some sample data.
Solution:
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie', 'Diana'], 'Age': [25, 30, 22, 35], 'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago']} df = pd.DataFrame(data) print(df)Exercise 2:
Add a new column to the DataFrame with the mean age of each city.
Solution:
df['Mean Age'] = df['Age'].mean() print(df)Exercise 3:
Filter the DataFrame to only include rows where the age is greater than the mean age.
Solution:
filtered_df = df[df['Age'] > df['Mean Age']] print(filtered_df)Exercise 4:
Create a scatter plot of the 'Age' vs. 'City' columns.
Solution:
import matplotlib.pyplot as plt plt.scatter(df['Age'], df['City']) plt.xlabel('Age') plt.ylabel('City') plt.title('Scatter Plot of Age vs City') plt.show()Exercise 5:
Calculate the sum of 'Age' for each city and add a new column to the DataFrame.
Solution:
df['City Sum'] = df['Age'].sum() print(df)Exercise 6:
Find the largest and smallest values in the 'Age' column and add them as new columns to the DataFrame.
Solution:
df['Smallest Age'] = df['Age'].min() df['Larg
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.