Gelir Hesaplamaları ve Özellik Mühendisliği
Satır kalemi gelirini hesaplayın, ay ve çeyrek sütunları oluşturun ve eşik değerin üzerindeki siparişler için indirim işareti ekleyin.
Gelir Hesaplamaları ve Özellik Mühendisliği, CoddyKit'te ücretsiz bir Pandas & NumPy Academy dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Pandas & NumPy Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Pandas & NumPy Academy kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“Gelir Hesaplamaları ve Özellik Mühendisliği” dersi ücretsiz mi?
Evet — “Gelir Hesaplamaları ve Özellik Mühendisliği” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Pandas & NumPy Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Pandas & NumPy Academy kursu toplamda 4 dersten oluşur.
“Gelir Hesaplamaları ve Özellik Mühendisliği” dersinde ne öğreneceğim?
Satır kalemi gelirini hesaplayın, ay ve çeyrek sütunları oluşturun ve eşik değerin üzerindeki siparişler için indirim işareti ekleyin. Pandas & NumPy Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Pandas & NumPy Academy öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Pandas & NumPy Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.
“Gelir Hesaplamaları ve Özellik Mühendisliği” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Pandas & NumPy Academy dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Pandas & NumPy Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Satış Veri Kümesini Yükleme ve Denetleme
- Gelir Hesaplamaları ve Özellik Mühendisliği
- Bölge ve Kategoriye Göre GroupBy Analizi
- Aylık Eğilim Görselleştirmesi