Practical Exercises Chapter 6
Exercise 1: Creating DataFrames
- Create a DataFrame from a dictionary containing columns for Name, Age, and Occupation.
- Add a new row to this DataFrame.
Solution:
import pandas as pd
# 1. Create a DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [28, 34, 45],
'Occupation': ['Engineer', 'Doctor', 'Artist']
})
# 2. Add a new row
new_row = {'Name': 'David', 'Age': 22, 'Occupation': 'Student'}
df = df.append(new_row, ignore_index=True)
print(df)
Exercise 2: Missing Data Handling
- Create a DataFrame with some missing values.
- Fill the missing values with the mean of the respective column.
Solution:
# 1. Create a DataFrame with missing values
df_missing = pd.DataFrame({
'A': [1, None, 3],
'B': [None, 5, 6]
})
# 2. Fill missing values...