0Pricing
Pandas & NumPy Academy · Lektion

Umsatzberechnung und Feature Engineering

Berechnen Sie den Umsatz je Position, erstellen Sie Spalten für Monat und Quartal und ergänzen Sie ein Rabattkennzeichen für Bestellungen über einem Schwellenwert.

Umsatzberechnung und Feature Engineering ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Häufig gestellte Fragen

Ist die Lektion „Umsatzberechnung und Feature Engineering“ kostenlos?

Ja — der vollständige Text von „Umsatzberechnung und Feature Engineering“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Umsatzberechnung und Feature Engineering“?

Berechnen Sie den Umsatz je Position, erstellen Sie Spalten für Monat und Quartal und ergänzen Sie ein Rabattkennzeichen für Bestellungen über einem Schwellenwert. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?

Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.

Wie lange dauert die Lektion „Umsatzberechnung und Feature Engineering“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?

Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Verkaufsdatensatz laden und prüfen
  2. Umsatzberechnung und Feature Engineering
  3. GroupBy-Analyse nach Region und Kategorie
  4. Monatliche Trendvisualisierung
← Zurück zu Pandas & NumPy Academy