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.

30 min 3 practice tasks
Learning Pandas for Data Analysis? Start Here. by Rob Mulla on YouTube

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 minimum amount were negative, or the maximum impressions absurdly 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.

1

Load the campaigns table

Load 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?
  1. pd.read_csv("campaigns.csv") returns a DataFrame.
  2. .shape is a pair (rows, columns), and it has no parentheses after it.
  3. n_rows, n_cols = campaigns.shape unpacks both at once.
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

First numbers from the orders table

Load orders.csv into a DataFrame named orders and compute:

  • total_amount: the sum of the amount column, rounded to 2 decimals
  • avg_amount: the average order amount, rounded to 2 decimals
  • n_customers: how many different customers placed orders (unique customer_ids)
Need a hint?
  1. orders["amount"] selects one column (a Series).
  2. Series have .sum(), .mean() and .nunique() methods.
  3. Wrap results in round(..., 2).
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Customers per segment

Load customers.csv into customers. Then create:

  • segment_counts: a Series with the number of customers in each segment

(use .value_counts())

  • top_segment: the name of the most common segment, as a string
Need a hint?
  1. customers["segment"].value_counts() counts each distinct value, largest first.
  2. The segment names are the Series' index, so segment_counts.index[0] is the most common one.
  3. segment_counts.idxmax() also works.
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country