Pandas Examples
Problem 1: Create a pandas Series representing the prices of three items (Apple: 1.50, Banana: 0.75, Orange: 1.25) using a dictionary. Then, apply a 10% discount to all items at once.
pandas-exercises.py
import pandas as pd
# 1. Create the Series from a dictionary
prices = pd.Series({'Apple': 1.50, 'Banana': 0.75, 'Orange': 1.25})
# 2. Apply a 10% discount (multiply by 0.90)
discounted_prices = prices * 0.90
print("Original Prices:
", prices)
print("
Discounted Prices:
", discounted_prices)
Problem 2: Create a DataFrame from a dictionary containing ‘Name’, ‘Age’, and ‘City’ for four people. Filter the DataFrame to display only the rows where the person is 30 years old or older.
pandas-exercises.py
import pandas as pd
# 1. Create the DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Age': [25, 32, 22, 45],
'City': ['New York', 'London', 'Paris', 'Tokyo']
}
df = pd.DataFrame(data)
# 2. Filter the DataFrame using a boolean condition
older_than_30 = df[df['Age'] >= 30]
print("Original DataFrame:
", df)
print("
People 30 or older:
", older_than_30)
*Problem 3: Create a DataFrame containing a list of employees with their ‘Department’ (e.g., Sales, IT) and ‘Salary’. Calculate the average (mean) salary for each department.
pandas-exercises.py
import pandas as pd
# 1. Create the DataFrame
data = {
'Department': ['Sales', 'IT', 'Sales', 'HR', 'IT', 'IT'],
'Salary': [60000, 80000, 65000, 55000, 90000, 85000]
}
df = pd.DataFrame(data)
# 2. Group by department and calculate the mean salary
average_salary = df.groupby('Department')['Salary'].mean()
print("Original DataFrame:
", df)
print("
Average Salary by Department:
", average_salary)