Section 3 · Lesson 3

Creating derived columns

Compute new columns like CTR, CPC and ROAS from existing ones, and summarize ratios correctly.

30 min 3 practice tasks
Python Pandas Tutorial (Part 6): Add/Remove Rows and Columns From DataFrames by Corey Schafer on YouTube

Raw tables rarely contain the numbers your manager asks about. daily_stats has impressions, clicks, spend, conversions and revenue, but the conversation is about CTR, CPC, CPA and ROAS. You build those as derived columns.

Column arithmetic is row by row

When you do arithmetic with two columns, pandas lines them up and calculates every row at once. No loop needed:

import pandas as pd

stats = pd.read_csv("daily_stats.csv")

stats["ctr"] = stats["clicks"] / stats["impressions"] * 100
stats["cpc"] = stats["spend"] / stats["clicks"]
stats["roas"] = stats["revenue"] / stats["spend"]

Assigning to a column name that doesn’t exist creates it; assigning to an existing one replaces it. You can also combine a column with a single number: stats["spend"] * 1.15 adds a 15% fee to every row.

The metrics you’ll compute most

Metric Formula Answers
CTR clicks ÷ impressions × 100 How often do people click?
CPC spend ÷ clicks What does one click cost?
CVR conversions ÷ clicks × 100 How many clicks turn into sales?
CPA spend ÷ conversions What does one conversion cost?
ROAS revenue ÷ spend Dollars back per dollar spent

Rounding and comparisons

stats["ctr"] = (stats["clicks"] / stats["impressions"] * 100).round(2)
stats["profitable"] = stats["revenue"] > stats["spend"]     # a True/False column
stats["profitable"].sum()                                   # number of profitable days
stats["profitable"].mean()                                  # share of profitable days

A True/False column is very useful: .sum() counts the True values, .mean() gives the share, and the column itself works as a filter mask.

Dividing by zero

Some days have zero conversions. Dividing by zero in pandas doesn’t crash; it produces inf (infinity), or NaN for 0 ÷ 0, and an inf will quietly wreck any average you take afterward. Blank out those rows instead:

stats["cpa"] = (stats["spend"] / stats["conversions"]).where(stats["conversions"] > 0)

.where(condition) keeps values where the condition is True and puts NaN (missing) everywhere else. Most pandas summaries skip NaN.

Text and date columns

Derived columns aren’t only math. The .str accessor applies string methods to every row:

campaigns = pd.read_csv("campaigns.csv")
campaigns["brand"] = campaigns["name"].str.split().str[0]   # 'Summit', 'BlueHarbor', ...
campaigns["name_upper"] = campaigns["name"].str.upper()

You’ll do the same with dates (.dt) in the last section.

Removing columns

campaigns = campaigns.drop(columns=["name_upper"])   # returns a new DataFrame

The video also adds rows with df.append(). That method was removed in pandas 2.0; today you’d write pd.concat([df, new_rows], ignore_index=True). The column techniques it shows work the same as ever.

Tip: overall CTR is not the average of daily CTRs. The average of the row-level CTRs treats a day with 3,000 impressions the same as a day with 3 million. Display campaigns get huge impression counts at very low CTRs, while search days are small but click-heavy, so the two numbers can be far apart. To report a metric for a group of rows, add up the parts first, then divide: stats["clicks"].sum() / stats["impressions"].sum() * 100. The third task shows you how big the gap is in this dataset.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Add CTR and CPC columns

Load daily_stats.csv into a DataFrame named stats. Add two new columns to it:

  • ctr: clicks ÷ impressions × 100 (a percentage), rounded to 2 decimals
  • cpc: spend ÷ clicks (cost per click in dollars), rounded to 2 decimals
Need a hint?
  1. Arithmetic on columns works row by row: stats["clicks"] / stats["impressions"].
  2. Assign to a new column name to create it: stats["ctr"] = ....
  3. Series have a .round(2) method; wrap the expression in parentheses first.
Python 3
import pandas as pd

stats = pd.read_csv("daily_stats.csv")

# add the ctr and cpc columns here

print(stats.head())
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

Which days were profitable?

Load daily_stats.csv into stats. Then: 1. Add a column roas (return on ad spend): revenue ÷ spend, rounded to 2 decimals. 2. Add a column profitable that is True when revenue is greater than spend. 3. Set n_profitable to the number of profitable rows (an integer).

Need a hint?
  1. A comparison of two columns, stats["revenue"] > stats["spend"], gives a True/False column.
  2. True counts as 1 when summed, so .sum() of a boolean column counts the Trues.
Python 3
import pandas as pd

stats = pd.read_csv("daily_stats.csv")

n_profitable = 0
print(n_profitable)
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

Overall CTR vs average daily CTR

Load daily_stats.csv into stats and compute two numbers, each rounded to 2 decimals:

  • overall_ctr: total clicks ÷ total impressions × 100 (one CTR for all rows combined)
  • avg_daily_ctr: first compute each row's CTR (clicks ÷ impressions × 100, not

rounded), then take the mean of those values

Print both. Are they close? (Read the tip at the end of the lesson for why not.)

Need a hint?
  1. stats["clicks"].sum() and stats["impressions"].sum() give the totals.
  2. For the average: build a CTR column first, then call .mean() on it.
Python 3
import pandas as pd

stats = pd.read_csv("daily_stats.csv")

overall_ctr = 0
avg_daily_ctr = 0

print(overall_ctr, avg_daily_ctr)
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