Revenue Calculations and Feature Engineering
Compute line-item revenue, create month and quarter columns, and add a discount flag for orders above a threshold.
Revenue Calculations and Feature Engineering is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Computing Line-Item Revenue
The most fundamental calculation in a sales dataset is line-item revenue: the product of quantity and unit price for each row. Create the column with a vectorised multiplication so NumPy processes every row simultaneously without a Python loop. This column becomes the basis for every aggregation in the analysis.
import pandas as pd
df = pd.read_parquet('sales_clean.parquet')
df['revenue'] = df['quantity'] * df['unit_price']
print(df[['quantity', 'unit_price', 'revenue']].head())Extracting Month and Quarter Columns
Grouping by calendar period is essential for trend analysis. Use the .dt accessor on a datetime column to extract year, month, and quarter. Storing these as separate integer columns makes groupby operations faster and lets you filter by period easily without repeated string parsing.
df['year'] = df['order_date'].dt.year
df['month'] = df['order_date'].dt.month
df['quarter'] = df['order_date'].dt.quarter
df['year_month'] = df['order_date'].dt.to_period('M')
print(df[['order_date', 'year', 'month', 'quarter', 'year_month']].head())Creating a Discount Flag
Business rules often define a discount flag: orders where the total exceeds a threshold receive a discount. Use np.where or a boolean comparison to create this binary column efficiently. A discount flag lets analysts compare revenue distributions between discounted and full-price orders in a single groupby call.
import numpy as np
DISCOUNT_THRESHOLD = 500
df['is_discounted'] = np.where(df['revenue'] >= DISCOUNT_THRESHOLD, 1, 0)
print(df['is_discounted'].value_counts())
print(df.groupby('is_discounted')['revenue'].mean())Computing Profit Margin Column
If the dataset includes a cost_price column, you can compute profit margin as (unit_price - cost_price) / unit_price. Use clip(lower=0) to cap any negative margins caused by data errors before further analysis. Margin columns enable profit-focused groupby aggregations alongside revenue.
df['margin'] = ((df['unit_price'] - df['cost_price']) / df['unit_price']).clip(lower=0)
print(df[['unit_price', 'cost_price', 'margin']].describe())Days Since First Order Feature
The number of days between a customer's first order and the current order is a useful customer tenure feature. Compute it by grouping on customer_id, taking the minimum date as the cohort date, and subtracting from each row's date. Timedelta arithmetic returns a column of timedelta64 values that you convert to integer days with .dt.days.
first_order = df.groupby('customer_id')['order_date'].transform('min')
df['days_since_first_order'] = (df['order_date'] - first_order).dt.days
print(df[['customer_id', 'order_date', 'days_since_first_order']].head())Order Size Bucket with pd.cut
Bin the revenue column into labelled size buckets using pd.cut() to create an ordinal feature for segmentation. Provide explicit bins and labels that match your business definitions of small, medium, and large orders. The resulting column is a Pandas Categorical, which groups efficiently.
bins = [0, 100, 500, 2000, float('inf')]
labels = ['Small', 'Medium', 'Large', 'Enterprise']
df['order_size'] = pd.cut(df['revenue'], bins=bins, labels=labels)
print(df['order_size'].value_counts())Cumulative Revenue Over Time
Sort the DataFrame by order_date and use cumsum() on the revenue column to track how total revenue accumulated over the year. This cumulative series makes it easy to spot whether revenue is growing linearly, accelerating, or plateauing, and is the basis for a waterfall or cumulative line chart.
df_sorted = df.sort_values('order_date')
df_sorted['cumulative_revenue'] = df_sorted['revenue'].cumsum()
print(df_sorted[['order_date', 'revenue', 'cumulative_revenue']].tail())Weekend vs. Weekday Feature
The dt.day_of_week property returns 0 (Monday) through 6 (Sunday). Flag Saturday (5) and Sunday (6) as weekend orders to test whether weekend buying behaviour differs from weekday. This is a common feature in retail EDA and A/B test analysis.
df['is_weekend'] = df['order_date'].dt.day_of_week >= 5
print(df.groupby('is_weekend')['revenue'].agg(['mean', 'count']))Rank Customers by Revenue
Identify your top customers by computing total revenue per customer_id with groupby().sum() and then ranking with .rank(ascending=False, method='dense'). Adding the rank back to the main DataFrame with map() lets you filter to top-N customers in a single boolean condition.
customer_revenue = df.groupby('customer_id')['revenue'].sum()
customer_rank = customer_revenue.rank(ascending=False, method='dense').astype(int)
df['customer_revenue_rank'] = df['customer_id'].map(customer_rank)
print(df[df['customer_revenue_rank'] <= 10][['customer_id', 'customer_revenue_rank']].drop_duplicates())Normalising Revenue with Z-Score
Normalise the revenue column to a Z-score so you can compare order sizes across different product categories that have very different price ranges. Use (df['revenue'] - df['revenue'].mean()) / df['revenue'].std(). Z-scores above 3 or below -3 are statistical outliers worth investigating before modelling.
mean_rev = df['revenue'].mean()
std_rev = df['revenue'].std()
df['revenue_zscore'] = (df['revenue'] - mean_rev) / std_rev
outliers = df[df['revenue_zscore'].abs() > 3]
print(f'Outlier orders: {len(outliers)}')Saving Feature-Enriched DataFrame
After adding computed columns, save the enriched DataFrame so every downstream notebook starts from the same consistent state. Use to_parquet() to preserve dtypes, especially the Categorical order_size column and the datetime order_date. Document the new columns in a short comment block at the top of the script.
# New columns added:
# revenue, year, month, quarter, year_month
# is_discounted, order_size, is_weekend
# days_since_first_order, customer_revenue_rank, revenue_zscore
df.to_parquet('sales_features.parquet', index=False)
print('Feature DataFrame saved:', df.shape)Quick Check
Test your understanding of Data Analysis concepts from this lesson.
Lesson Recap
In this lesson you learned: computing revenue and profit margin columns, extracting temporal features with the .dt accessor, and engineering features like discount flags, order size buckets, and customer ranks. Next up we explore groupby analysis by region and category.
Frequently asked questions
Is the “Revenue Calculations and Feature Engineering” lesson free?
Yes — the full text of “Revenue Calculations and Feature Engineering” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Revenue Calculations and Feature Engineering”?
Compute line-item revenue, create month and quarter columns, and add a discount flag for orders above a threshold. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Revenue Calculations and Feature Engineering” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Loading and Auditing the Sales Dataset
- Revenue Calculations and Feature Engineering
- GroupBy Analysis by Region and Category
- Monthly Trend Visualisation