Data analysis with pandas · Lesson 1 of 15
What pandas is: your first DataFrame
Meet pandas, the Python library for tables. Build your first DataFrame from a dictionary, look at its shape and columns and add up a column.
pandas is a Python library for working with tables of data: rows and columns, like a spreadsheet. You can load a file, clean it, filter it, add it up by group and draw a chart, all with a few lines of code. Data analysts, scientists and accountants use it every day.
A library is code someone else wrote that you load with import. Everyone imports pandas under the short name pd, so you will see pd. in front of its functions in every example on the web.
pip install pandas in a terminal.Your first DataFrame
The main object in pandas is the DataFrame: a table with named columns. The easiest way to make one is from a dictionary where each key is a column name and each value is a list with that column's values.
import pandas as pd
data = {
"fruit": ["apple", "banana", "cherry", "mango"],
"price": [1.20, 0.50, 4.00, 2.10],
"stock": [30, 45, 12, 8],
}
df = pd.DataFrame(data)
print(df)fruit price stock 0 apple 1.2 30 1 banana 0.5 45 2 cherry 4.0 12 3 mango 2.1 8
pandas prints the table with the column names on top and a row number on the left.
The numbers 0 to 3 on the left are the index: a label for every row. pandas adds 0, 1, 2 … when you do not give your own labels. Each column holds one kind of value: text in fruit, decimals in price, whole numbers in stock.
How big is the table?
df.shape gives the number of rows and columns as a tuple. df.columns lists the column names, and len() counts the rows.
import pandas as pd
df = pd.DataFrame({
"fruit": ["apple", "banana", "cherry", "mango"],
"price": [1.20, 0.50, 4.00, 2.10],
"stock": [30, 45, 12, 8],
})
print(df.shape)
print(list(df.columns))
print(len(df), "rows")(4, 3) ['fruit', 'price', 'stock'] 4 rows
Working with one column
Square brackets with a column name give you that column. You can add it up, find the largest value or the average straight away, with no loop.
import pandas as pd
df = pd.DataFrame({
"fruit": ["apple", "banana", "cherry", "mango"],
"price": [1.20, 0.50, 4.00, 2.10],
"stock": [30, 45, 12, 8],
})
print("Items in stock:", df["stock"].sum())
print("Most expensive:", df["price"].max())
print(f"Average price: {df['price'].mean():.2f} €")Items in stock: 95 Most expensive: 4.0 Average price: 1.95 €
An f-string with :.2f rounds the average to 2 decimals.
Rows as dictionaries
If your data comes as one dictionary per row (a common shape for data from a web form or an app), pass a list of them to pd.DataFrame. Each key becomes a column.
import pandas as pd
rows = [
{"name": "Ana", "city": "Porto", "age": 34},
{"name": "Ben", "city": "Leeds", "age": 28},
{"name": "Chloe", "city": "Lyon", "age": 41},
]
people = pd.DataFrame(rows)
print(people)
print("Oldest:", people["age"].max())name city age 0 Ana Porto 34 1 Ben Leeds 28 2 Chloe Lyon 41 Oldest: 41
✎ Exercise
Build a DataFrame temps with two columns: city (Oslo, Rome, Cairo) and temp (4, 15, 24). Print the table, then print the highest temperature.
Hint: Pass a dictionary of two lists to pd.DataFrame, then use temps["temp"].max().
import pandas as pd
# your code here
Expected output:
city temp 0 Oslo 4 1 Rome 15 2 Cairo 24 Highest: 24
Show a solution
import pandas as pd
temps = pd.DataFrame({
"city": ["Oslo", "Rome", "Cairo"],
"temp": [4, 15, 24],
})
print(temps)
print("Highest:", temps["temp"].max())city temp 0 Oslo 4 1 Rome 15 2 Cairo 24 Highest: 24
Check yourself
1. What is a DataFrame?
A DataFrame is pandas' table: columns with names, and an index that labels each row.
2. A DataFrame has 6 rows and 3 columns. What does df.shape give?
shape is (rows, columns).
3. Why do most examples write import pandas as pd?
as pd is just a nickname. It saves typing, and because everyone uses it, code from different people looks the same.