0Pricing
Pandas & NumPy Academy · درس

حساب الإيرادات وهندسة الميزات

احسب إيرادات بنود الطلب، وأنشئ عمودي الشهر والربع، وأضف علامة خصم للطلبات التي تتجاوز عتبة معينة.

حساب الإيرادات وهندسة الميزات درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

ماذا ستتعلم في «حساب الإيرادات وهندسة الميزات»؟

احسب إيرادات بنود الطلب، وأنشئ عمودي الشهر والربع، وأضف علامة خصم للطلبات التي تتجاوز عتبة معينة. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟

لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «حساب الإيرادات وهندسة الميزات»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟

نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تحميل مجموعة بيانات المبيعات وتدقيقها
  2. حساب الإيرادات وهندسة الميزات
  3. تحليل GroupBy حسب المنطقة والفئة
  4. تصور الاتجاه الشهري
← العودة إلى Pandas & NumPy Academy