PANDAS
HODP Spring 2025 BOOTCAMP
ANNOUNCEMENTS
End Goal
Your Article Here!
THE PLAN
Review - Modeling
WHAT IS MODELING
WHAT IS MODELING
Review - Data Structures
Lists
Data storage type that is ordered and can store different types of information
To declare a list, use brackets [ ] to enclose the list and commas , to separate each item.
my_list = [‘red’, ‘green’, ‘blue’, ‘yellow’, ‘white’, ‘black’]
Lists are indexed! Each value in the list is assigned an index
More methods
Add element to list
lst.append("z")
Remove element from list
lst.remove("z")
Insert an element into a specific index in the list
lst.insert(2, "zzz")
Reverse list
lst.reverse()
Sort list
lst.sort()
Extend a list (different than append)!
lst.extend(thing)
List methods are done “in place”, which means you do not need to do �lst = lst.append(“z”)! Typing lst.append(“z”) will add “z” to the list directly.
Dictionaries
grades = {
"freshman": 9,
"sophomore": 10,
}
�“Freshman” is a key, 9 is the value, which you can access with grades[“freshman”]
Adding Elements to the Dictionary
We can add elements (or replace elements) using hopefully familiar syntax!
grades[“junior”] = 11
grades[“senior”] = 12
grades = {
"freshman": 9,
"sophomore": 10,
“junior”: 11,
“senior”: 12,
}
To delete an element, you can do del grades[“junior”].
KeyErrors and Iterations
CAUTION: What happens if you try to access a key that is NOT in the dictionary?
Bypassing:
Checking:
Functions
def square(x):
return x**2
square(5)
>> 25
Pandas
FOLLOW ALONG ON DEEPNOTE
WHAT IS PANDAS
Conventions:
“import pandas as pd” // always like this by convention, do NOT change
df = name of dataframe
s = name of series
ALL PANDAS COMMANDS WILL HAVE THE PREFIX “pd.”
PANDAS SPECIFIC STRUCTURES
DFs - List of Dictionaries
DFs - Dictionary of Lists
DFs - Reading a CSV
The command is df = pd.read_csv(path):
Exercise 1
Go onto Deepnote and give Exercise 1 a shot! If you completed it successfully, you should be able to see your loaded in Data.
Basic Data Exploration
EDA Continued
Exercise 2
Go onto Deepnote and give Exercise 2 a shot! Note:
Every time you want to display something, you either need to create a new code block (preferred) or use the print function. We prefer the first, since the formatting looks a bit cleaner!
Indexing
result = df.loc['b', ['Name', 'Age']] print(result)
result = df.iloc[1, [0, 1]] print(result)
Multiple Entry Access
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [25, 30, 35, 40, 45],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd', 'e'])
result = df.loc['b':'d']
print(result)
result = df.iloc[1:3]
print(result)
Exercise 3
Go onto Deepnote and give Exercise 3 a go!
Restructuring Dataframes - Sort
Restructuring Dataframes - Func
Start with:
// start
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)
Original (top) vs post-restructure (bottom)
// restructuring
df['Bonus'] = df['Salary'] * 0.10
df['Age'] = df['Age'].apply(add_ten)
// end
What might add_ten look like?
| Name | Age | Salary |
0 | Alice | 25 | 50000 |
1 | Bob | 30 | 60000 |
2 | Charlie | 35 | 70000 |
| Name | Age | Salary | Bonus |
0 | Alice | 35 | 50000 | 5000.0 |
1 | Bob | 40 | 60000 | 6000.0 |
2 | Charlie | 45 | 70000 | 7000.0 |
Restructuring Dataframes - Drop
Start with:
// start
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000],
‘Bonus’: [5000.0, 6000.0, 7000.0]}
df = pd.DataFrame(data) Original (top) vs post-restructure (bottom)
df.drop('Bonus', axis=1, inplace=True)
// axis = 1 means column
Row drop: df.drop(1, axis=0, inplace=True)
| Name | Age | Salary |
0 | Alice | 25 | 50000 |
1 | Bob | 30 | 60000 |
2 | Charlie | 35 | 70000 |
| Name | Age | Salary | Bonus |
0 | Alice | 25 | 50000 | 5000.0 |
1 | Bob | 30 | 60000 | 6000.0 |
2 | Charlie | 45 | 70000 | 7000.0 |
Filtering
Start with:
// start
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000],
‘Bonus’: [5000.0, 6000.0, 7000.0]}
df = pd.DataFrame(data) Original (top) vs post-restructure (bottom)
filtered_df = df[df['Age'] > 28]
| Name | Age | Salary | Bonus |
0 | Alice | 25 | 50000 | 5000.0 |
1 | Bob | 30 | 60000 | 6000.0 |
2 | Charlie | 45 | 70000 | 7000.0 |
| Name | Age | Salary | Bonus |
1 | Bob | 30 | 60000 | 6000.0 |
2 | Charlie | 45 | 70000 | 7000.0 |
Simple Plotting
Make sure you have import matplotlib.pyplot as plt
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000],
‘Bonus’: [5000.0, 6000.0, 7000.0]}
df = pd.DataFrame(data)
df.plot()
// might need this if not last line of notebook cell
// plt.show()
| Name | Age | Salary | Bonus |
0 | Alice | 25 | 50000 | 5000.0 |
1 | Bob | 30 | 60000 | 6000.0 |
2 | Charlie | 45 | 70000 | 7000.0 |
Common Dangers
Exporting
cleaned_df_path = ‘/path/to/your/file/desired_file_name.csv’
// optional - will only run if the file if the desired file doesn’t exist yet
if not os.path.exists(cleaned_df_path):
df.to_csv(cleaned_df_path, index=False)
Project Time
https://tinyurl.com/hodp-spring25-project
Use the link on the first page of the form to find people and their interests. As groups form, we will try to update that spreadsheet (which is also here)
https://docs.google.com/spreadsheets/d/1QpwyljIJ8NnM-AN6ggfeG4PFC4bRGS8kgp8HMtTc8yQ/edit?gid=0#gid=0
Attendance Code: pd