Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 35

Feature Engineering from Existing Data

Recommended resources

Welcome to the next lesson in our feature engineering module. So far, we've focused on preparing existing features for our models by encoding categorical data and scaling numerical data. Now, we move into one of the most creative and impactful aspects of machine learning: feature construction. This is the art of creating entirely new, more informative features from the ones you already have.

This lesson directly addresses your interest in getting hands-on with practical data manipulation. We will explore how to derive new features from various data types—including numerical, datetime, and text columns—often guided by domain knowledge. Mastering these techniques will significantly boost your ability to build powerful predictive models.

1. The Landscape of Feature Construction

Feature construction, also called feature generation, is about making the data we already have more useful. Instead of just cleaning or scaling features, we're adding new columns to our dataset that explicitly represent patterns or relationships that a model might otherwise struggle to find on its own.

This can involve anything from simple arithmetic to complex text processing. The image below provides a great high-level map of the different kinds of features we can create.

This diagram shows four common categories for feature construction: creating new features from numerical, categorical, date/time, and text data. We will cover techniques for most of these today.

Let's begin with a video that introduces the concept and provides some foundational examples.

Feature Engineering Full Course - in 1 Hour Beginner Level

The video "Feature Engineering Full Course" from Analytics Vidhya provides an excellent introduction to what feature engineering entails.

Watch the introductory section from what is feature engineering. Pay attention to the core idea: we're not adding new data, but extracting more information from existing data. The examples of creating 'age' from 'birth year' and 'income band' from 'income' are perfect illustrations of this concept.


2. Creating Features from Numerical and Domain-Specific Data

One of the most straightforward ways to construct features is by combining or transforming existing numerical and categorical columns. Your intuition about the data and the problem domain plays a huge role here.

Common techniques include:

  • Interaction Features: Creating new features by performing mathematical operations between two or more columns (e.g., sum, ratio, product). For example, in a loan application dataset, a debt_to_income_ratio is far more predictive than just debt and income alone.
  • Binning (Discretization): Grouping a continuous numerical feature into a set of discrete categories or "bins." For example, converting a specific age into an age_group like 'Child', 'Adult', or 'Senior'.
  • Domain-Specific Extraction: Using your knowledge of how the data is structured to pull out meaningful substrings or codes. For instance, if a product ID FD-101 always starts with a two-letter category code, you can extract that code (FD) into a new 'product_category' feature.

The following video provides concrete examples for all these techniques.

Feature Engineering Full Course - in 1 Hour Beginner Level

This video demonstrates several practical feature construction techniques using Python and Pandas.

Please watch the following three segments: Creating Features from Existing Features: This part shows two excellent examples of domain-specific feature construction: Extracting a product category (FD, DR, NC) from an Item_Identifier string. Combining SibSp and Parch to create a Family_Size feature in the Titanic dataset. Extracting a passenger's Title (Mr., Mrs., etc.) from their name. Feature Interaction: Here, you'll see how to create interaction features like Total_Income (by adding two income columns) and Loan_Income_Ratio (by dividing loan amount by income). Binning Continuous Variables: This section demonstrates how to convert a continuous Age variable into categorical bins (Child, Teenager, etc.) using pd.cut.


3. Harnessing the Power of Time: Datetime Features

Raw date and time columns (e.g., 2023-10-26 14:35:01) are often not directly useful to machine learning models. However, they contain a wealth of information that can be extracted to capture trends, seasonality, and cyclical patterns.

Common datetime features include:

  • Time Components: Year, month, day, day of the week, hour, minute, quarter, week of the year.
  • Cyclical Features: Often, features like 'day of the week' or 'month' are cyclical (e.g., Sunday is next to Monday; December is next to January). We can represent this relationship using sine and cosine transformations, a topic we'll explore in the next lesson.
  • Boolean Flags: is_weekend, is_holiday, is_month_start. These can capture specific behavioral patterns.
  • Time Differences: Calculating elapsed time between events, such as a customer's age_at_purchase or days_since_last_login.

The next video segment provides a comprehensive walkthrough of datetime feature engineering in Pandas.

Feature Engineering Full Course - in 1 Hour Beginner Level

This segment is a deep dive into creating features from datetime columns.

Watch the section from Feature Engineering with Datetime Variables. This is a detailed section, so focus on grasping the variety of features you can create. Key moments include: Converting a string column to a proper datetime object using pd.to_datetime (conversion). Extracting components like hour, minute, and day of the week using the .dt accessor (component extraction). Creating a boolean is_weekday flag (weekday flag). Calculating the difference between two dates to get an age (date difference).

For a quick reference, the article "7 Pandas Tricks for Time-Series Feature Engineering" is a great resource. Specifically, sections 1. Extracting Datetime Components and 5. Measuring Time Between Events provide concise code snippets for the techniques shown in the video.


4. Extracting Signals from Unstructured Text

Your background in NLP will serve you well here. As you know, models require numerical input, so raw text must be converted into a feature vector. While complex methods like BERT embeddings (which we'll touch on later in the course) provide state-of-the-art performance, you can often get great results with simpler, more direct features.

Some simple but effective text features include:

  • Text Statistics: Length of the text, word count, sentence count, average word length.
  • Keyword Counts: Counting the occurrences of specific, domain-relevant words.
  • TF-IDF (Term Frequency-Inverse Document Frequency): This is a classic technique that creates a numerical feature for each word in your vocabulary, weighted by how important that word is to a specific document relative to the entire corpus of documents.

Let's focus on TF-IDF as a foundational technique for text feature engineering.

3 Feature Engineering Techniques for Unstructured Text ...

This article provides an excellent, intuition-first explanation of three key text feature engineering methods.

Please read the section "1. The Statistical Foundation: TF-IDF Vectorization". It clearly explains the logic behind TF-IDF—penalizing common words and rewarding unique ones—and provides a clean implementation using scikit-learn's TfidfVectorizer.


5. Putting It All Together: A Practical Example

Let's consolidate these ideas with a Python script. Here, we'll take a small, synthetic dataset and apply several of the feature construction techniques we've discussed.

import pandas as pd
import numpy as np




# 1. Create a sample DataFrame
data = {
    'transaction_id': range(5),
    'product_sku': ['SHIRT-BL-M', 'PANT-BK-L', 'SHOE-WT-10', 'SHIRT-RD-M', 'ACC-SLV-OS'],
    'purchase_timestamp': pd.to_datetime(['2023-01-14 10:00:00', '2023-01-14 19:30:00', 
                                      '2023-01-15 12:00:00', '2023-01-16 09:15:00', '2023-01-16 15:45:00']),
    'unit_price': [25.00, 55.00, 80.00, 28.00, 15.00],
    'quantity': [2, 1, 1, 3, 5]
}
df = pd.DataFrame(data)
print("--- Original Data ---")
print(df)




# 2. Construct new features
# Numerical interaction feature
df['total_sale'] = df['unit_price'] * df['quantity']




# Datetime features
df['purchase_day_of_week'] = df['purchase_timestamp'].dt.day_name()
df['purchase_hour'] = df['purchase_timestamp'].dt.hour
df['is_weekend'] = df['purchase_timestamp'].dt.weekday.isin([5, 6])




# Text/Domain-specific features from 'product_sku'
# You can use .str.split() for this
df['product_category'] = df['product_sku'].str.split('-').str[0]
df['product_color'] = df['product_sku'].str.split('-').str[1]

print("\n--- Data with Constructed Features ---")
print(df[['transaction_id', 'total_sale', 'purchase_day_of_week', 'purchase_hour', 'is_weekend', 'product_category', 'product_color']])

In this example, we created:

  • A numerical feature (total_sale) by multiplying two existing columns.
  • Several datetime features to capture when a purchase was made.
  • Two categorical features by parsing a structured string (product_sku), demonstrating the use of domain knowledge.

This is the essence of practical feature construction.


Conclusion

In this lesson, you moved beyond preparing data to actively creating it. Feature construction is where data science becomes a creative process, allowing you to inject domain knowledge and uncover hidden signals for your model.

Key Takeaways:

  • Feature construction is the process of creating new features from existing ones to improve model performance.
  • Numerical features can be combined through mathematical operations (ratios, sums) or binned into categories.
  • Datetime features are extremely valuable for capturing seasonality, trends, and cycles. Use the .dt accessor in Pandas to extract components like day of the week, hour, and month.
  • Text features can range from simple statistics (like word count) to sophisticated representations like TF-IDF, which weights words by their importance.
  • Domain knowledge is your most powerful tool. Understanding your data's structure and meaning will guide you toward creating the most impactful features.

In our next lesson, we will dive deeper into a specific and powerful type of feature construction: creating polynomial features and interaction terms. This automated technique is excellent for capturing non-linear relationships in your data.