0Pricing
Pandas & NumPy Academy · 강의

매출 계산과 특성 공학

개별 항목 매출을 계산하고 월·분기 열을 만들며 기준값을 초과하는 주문에 할인 플래그를 추가합니다.

매출 계산과 특성 공학은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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.

자주 묻는 질문

“매출 계산과 특성 공학” 강의는 무료인가요?

네 — “매출 계산과 특성 공학” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“매출 계산과 특성 공학”에서 뭘 배우나요?

개별 항목 매출을 계산하고 월·분기 열을 만들며 기준값을 초과하는 주문에 할인 플래그를 추가합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“매출 계산과 특성 공학” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 판매 데이터 세트 불러오기와 감사
  2. 매출 계산과 특성 공학
  3. 지역 및 범주별 GroupBy 분석
  4. 월별 추세 시각화
← Pandas & NumPy Academy(으)로 돌아가기