Section 3 · Lesson 1
DataFrames, Series and read_csv
Load a CSV file into a DataFrame and size it up with head, shape, dtypes and describe.
Everything so far was plain Python. Now you’ll meet pandas, the library analysts use to work with tables. If you’ve used Excel or SQL, the ideas will feel familiar: rows, columns, filters, totals. The difference is that every step is written down as code, so it’s repeatable and easy to check.
Two core objects
| Object | Think of it as | Example |
|---|---|---|
| DataFrame | a whole table (rows and named columns) | the orders table |
| Series | one column, with a label for each row | orders["amount"] |
Every DataFrame has an index: the row labels shown on the left when you print it. When you load a CSV, the index is simply 0, 1, 2, and so on.
Loading a CSV
By convention pandas is imported as pd:
import pandas as pd
orders = pd.read_csv("orders.csv")
In this course the five practice tables (advertisers, campaigns, daily_stats,
customers, orders) are CSV files in the sandbox’s working folder, so the file name
alone is enough. On your own computer you’d pass a path such as "data/orders.csv".
Your first-look checklist
Whenever you get a new dataset, spend two minutes on these before analyzing anything:
| Code | What it tells you |
|---|---|
df.head() / df.tail(3) |
the first 5 / last 3 rows |
df.shape |
(rows, columns), an attribute, so no () |
df.columns |
the column names |
df.dtypes |
the type of each column |
df.info() |
columns, types and non-missing counts in one view |
df.describe() |
count, mean, std, min, quartiles and max of numeric columns |
orders.shape # (900, 6)
orders.dtypes
# id int64
# customer_id int64
# campaign_id float64
# order_date str
# amount float64
# status str
Two things to notice. Text columns show the type str. And campaign_id is float64
even though IDs are whole numbers: some orders have no campaign, and a missing value
(NaN, “not a number”) forces the column to decimals. Clues like that are exactly why
you inspect first.
Working with a single column
Select a column with square brackets and you get a Series with handy methods:
amount = orders["amount"]
amount.sum() # total of all orders
amount.mean() # average order value
amount.max() # largest order
orders["customer_id"].nunique() # number of distinct customers
orders["status"].value_counts() # rows per status, largest first
value_counts() is the fastest way to understand a category column. It returns a Series
whose index holds the categories and whose values are the counts:
orders["status"].value_counts()
# status
# completed 768
# refunded 74
# cancelled 58
Building a DataFrame yourself
You can also create a DataFrame from a dictionary of lists, which is handy for small lookup tables or quick tests:
targets = pd.DataFrame({
"channel": ["search", "social", "video"],
"target_cpc": [1.50, 1.00, 0.80],
})
Tip:
describe()is a quick sanity check. If the minimumamountwere negative, or the maximumimpressionsabsurdly large, you’d want to know before reporting a total to anyone.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Load the campaigns table
DoneLoad campaigns.csv into a DataFrame named campaigns. Then use its .shape to set:
n_rows: the number of rows (campaigns)n_cols: the number of columns
Need a hint?
pd.read_csv("campaigns.csv")returns a DataFrame..shapeis a pair(rows, columns), and it has no parentheses after it.n_rows, n_cols = campaigns.shapeunpacks both at once.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
campaigns = ... # load campaigns.csv here
n_rows = 0
n_cols = 0
print(n_rows, n_cols)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)First numbers from the orders table
DoneLoad orders.csv into a DataFrame named orders and compute:
total_amount: the sum of theamountcolumn, rounded to 2 decimalsavg_amount: the average order amount, rounded to 2 decimalsn_customers: how many different customers placed orders (uniquecustomer_ids)
Need a hint?
orders["amount"]selects one column (a Series).- Series have
.sum(),.mean()and.nunique()methods. - Wrap results in
round(..., 2).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
orders = pd.read_csv("orders.csv")
total_amount = 0
avg_amount = 0
n_customers = 0
print(total_amount, avg_amount, n_customers)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Customers per segment
DoneLoad customers.csv into customers. Then create:
segment_counts: a Series with the number of customers in eachsegment
(use .value_counts())
top_segment: the name of the most common segment, as a string
Need a hint?
customers["segment"].value_counts()counts each distinct value, largest first.- The segment names are the Series' index, so
segment_counts.index[0]is the most common one. segment_counts.idxmax()also works.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
customers = pd.read_csv("customers.csv")
segment_counts = None
top_segment = ""
print(segment_counts)
print(top_segment)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)