In this collaborative coding exercise, weβll explore Pandas Series, a fundamental data structure in the Pandas library. Youβll work together to create, manipulate, and analyze Series objects.
Feel free to refer to this cheatsheet throughout the exercise if you need a quick reminder about syntax or functionality.
Setup
First, letβs import the necessary libraries and create a sample Series.
import pandas as pdimport numpy as np# Create a sample Seriesfruits = pd.Series(['apple', 'banana', 'cherry', 'date', 'elderberry'], name='Fruits')print(fruits)
0 apple
1 banana
2 cherry
3 date
4 elderberry
Name: Fruits, dtype: object
Exercise 1: Creating a Series
Work together to create a Series representing the prices of the fruits in our fruits Series.
# Your code here# Create a Series called 'prices' with the same index as 'fruits'# Use these prices: apple: $0.5, banana: $0.3, cherry: $1.0, date: $1.5, elderberry: $2.0
Exercise 2: Series Operations
Collaborate to perform the following operations:
Calculate the total price of all fruits.
Find the most expensive fruit.
Apply a 10% discount to all fruits priced over $1.0.
# Your code here# 1. Calculate the total price of all fruits# 2. Find the most expensive fruit# 3. Apply a 10% discount to all fruits priced over $1.0
Exercise 3: Series Analysis
Work as a team to answer the following questions:
What is the average price of the fruits?
How many fruits cost less than $1.0?
What is the price range (difference between max and min prices)?
# Your code here# 1. Calculate the average price of the fruits# 2. Count how many fruits cost less than $1.0# 3. Calculate the price range (difference between max and min prices)
Exercise 4: Series Manipulation
Collaborate to perform these manipulations on the fruits and prices Series:
Add a new fruit βfigβ with a price of $1.2 to both Series using pd.concat
Remove βbananaβ from both Series.
Sort both Series by fruit name (alphabetically).
# Your code here# 1. Add 'fig' to both Series (price: $1.2)# 2. Remove 'banana' from both Series# 3. Sort both Series alphabetically by fruit name
Conclusion
In this collaborative exercise, youβve practiced creating, manipulating, and analyzing Pandas Series. Youβve learned how to perform basic operations, apply conditions, and modify Series objects. These skills will be valuable as you work with more complex datasets in the future.
Discussion Questions
What advantages does using a Pandas Series offer compared to using a Python list or dictionary?
Can you think of a real-world scenario where you might use a Pandas Series instead of a DataFrame?
What challenges did you face while working with Series in this exercise, and how did you overcome them?
Discuss these questions with your team and share your insights.