5 Python and Pandas Problems to Practice Before an AI/ML Interview

Many candidates can explain complex concepts like self-attention in Transformers but struggle with practical tasks such as cleaning a messy CSV file during live coding interviews. Despite advances in Generative AI and LLMs, effective machine learning depends on high-quality data. Practicing Python and Pandas problems before an AI/ML interview remains one of the most effective ways to prepare for your career.

Hiring managers are not seeking candidates who have memorized syntax. They want to see if you can transform raw, unstructured production data into reliable features using efficient, robust code.

This article presents five problems that reflect the types of challenges you will encounter in a live AI/ML coding interview.

Python and Pandas Problems to Practice Before an AI/ML Interview

During technical screenings, interviewers use Pandas problems to evaluate two things: your data intuition and your ability to think in vectorized operations.

A common mistake among beginners is treating a Pandas DataFrame as a list of rows and iterating with a for loop or .iterrows(). In production, loops do not scale. Using loops on large datasets during an interview suggests limited experience with real-world data pipelines.

Below are five problems that reflect the challenges commonly encountered in live AI/ML coding interviews.

Problem 1: Sanitize Messy E-Commerce Logs

Question: You are given a DataFrame df containing user_id, email, and purchase_amount. The email column has leading/trailing whitespace and inconsistent casing; purchase_amount is stored as strings with $ and , symbols (e.g., “$1,200.50”), and there are duplicate logs where the same user and email appear multiple times. Keep only the first occurrence of each (user_id, email) pair after cleaning the strings, and convert purchase_amount to a float.

import pandas as pd

def sanitize_logs(df: pd.DataFrame) -> pd.DataFrame:
    df = df.copy()
    
    # Clean email strings first so duplicates with different casing are caught
    df['email'] = df['email'].str.strip().str.lower()
    
    # Remove duplicate records based on user_id and cleaned email
    df = df.drop_duplicates(subset=['user_id', 'email'], keep='first')
    
    # Strip currency symbols and commas, then cast to float
    df['purchase_amount'] = (
        df['purchase_amount']
        .str.replace('$', '', regex=False)
        .str.replace(',', '', regex=False)
        .astype(float)
    )
    
    return df

The order of operations is important. Many candidates use drop_duplicates() before standardizing text, which can miss duplicates such as “User@gmail.com ” and “user@gmail.com”. Always normalize string keys before removing duplicates.

Problem 2: Contextual Sensor Imputation

Question: You have an IoT dataset df with sensor_id, location_type, and temperature. Some temperature readings are NaN. Instead of dropping rows or using a global average, impute missing temperature values with the median temperature for that specific location_type. If an entire location_type has NaN values, fall back to the global median.

import pandas as pd

def impute_sensor_data(df: pd.DataFrame) -> pd.DataFrame:
    df = df.copy()
    
    # Calculate group-level median aligned with the original DataFrame's index
    group_medians = df.groupby('location_type')['temperature'].transform('median')
    
    # Fill with group median first, then fallback to global median
    df['temperature'] = df['temperature'].fillna(group_medians)
    df['temperature'] = df['temperature'].fillna(df['temperature'].median())
    
    return df

Many candidates use groupby().apply(), which is slow and can disrupt the index. Using .transform('median') is a more efficient solution, as it applies the group calculation to the original row indices in a single, vectorized step. Additionally, explain to your interviewer why you chose the median over the mean, since outliers in sensor data can skew the mean.

Problem 3: High-Value Customer Cohort Summary

Question: Given a transaction table df with user_id, transaction_id, category, and amount, return a summary DataFrame for each user_id showing their total_spent, transaction_count, and top_category (the category where they spent the most total money). Return only users who have at least 3 transactions.

import pandas as pd

def summarize_high_value_users(df: pd.DataFrame) -> pd.DataFrame:
    # Step 1: Aggregate overall user metrics
    user_summary = df.groupby('user_id').agg(
        total_spent=('amount', 'sum'),
        transaction_count=('transaction_id', 'count')
    )
    
    # Step 2: Find the top category by spend for each user
    cat_spend = (
        df.groupby(['user_id', 'category'])['amount']
        .sum()
        .reset_index()
        .sort_values(['user_id', 'amount'], ascending=[True, False])
    )
    top_cat = cat_spend.drop_duplicates('user_id').set_index('user_id')['category']
    
    # Step 3: Combine and filter
    user_summary['top_category'] = top_cat
    result = user_summary[user_summary['transaction_count'] >= 3].reset_index()
    
    return result

Avoid using pd.Series.mode within .agg() to identify top categories, as it is slow and can behave unpredictably when ties occur. Instead, sort the grouped category sums and use drop_duplicates('user_id') for a deterministic, readable, and scalable solution.

Problem 4: Point-in-Time User Feature Join

Question: You are building a fraud detection model. You have a transactions DataFrame (user_id, tx_time, amount) and a credit_scores DataFrame (user_id, updated_at, credit_score). Merge these tables so that each transaction is matched with the user’s most recent credit_score available at or before tx_time.

import pandas as pd

def merge_point_in_time(transactions: pd.DataFrame, credit_scores: pd.DataFrame) -> pd.DataFrame:
    # Ensure both timestamp columns are datetime objects and sorted
    tx_sorted = transactions.sort_values('tx_time')
    scores_sorted = credit_scores.sort_values('updated_at')
    
    # Perform a backward rolling join per user_id
    merged_df = pd.merge_asof(
        tx_sorted,
        scores_sorted,
        left_on='tx_time',
        right_on='updated_at',
        by='user_id',
        direction='backward'
    )
    
    return merged_df

This scenario tests your understanding of data leakage. Using a standard pd.merge() on user_id can incorrectly match a transaction from January with a credit score updated in March. Addressing data leakage and resolving it with pd.merge_asof() demonstrates your awareness of production machine learning challenges.

Problem 5: Rolling Spend Velocity & Time Deltas

Question: Given a DataFrame df with user_id, tx_time, and amount, create two new features for an anomaly detection model: hours_since_last_tx (hours elapsed since the user’s previous transaction, filled with -1 for their very first transaction) and rolling_3_tx_avg (the average amount of the user’s current and previous 2 transactions).

import pandas as pd

def engineer_velocity_features(df: pd.DataFrame) -> pd.DataFrame:
    df = df.sort_values(['user_id', 'tx_time']).copy()
    
    # Calculate time elapsed in hours since the previous transaction per user
    time_diff = df.groupby('user_id')['tx_time'].diff()
    df['hours_since_last_tx'] = (time_diff.dt.total_seconds() / 3600.0).fillna(-1.0)
    
    # Calculate rolling 3-transaction average per user
    df['rolling_3_tx_avg'] = (
        df.groupby('user_id')['amount']
        .transform(lambda x: x.rolling(window=3, min_periods=1).mean())
    )
    
    return df

Raw timestamps provide limited value to tree-based models such as XGBoost or LightGBM. Predictive power comes from velocity, or how quickly a user acts compared to their historical baseline. Always sort your DataFrame by entity and time before applying .diff() or .rolling().

Building a Structured Preparation Strategy

Many learners who struggle in interviews do so not from lack of effort, but because they memorize isolated questions rather than understanding underlying patterns. This motivated me to write my book, Cracking your First AI/ML Interview.

Rather than providing a list of definitions to memorize, the book is designed to help you identify what interviewers are actually testing, from Python, Pandas, and SQL preprocessing patterns to ML system design, project walk-throughs, and modern LLM/RAG scenarios.

If you seek a structured guide to connect technical skills with real business reasoning, consider making it part of your daily preparation routine.

The Takeaway

Do not let the rapid pace of AI advancements cause you to overlook the fundamentals. Every advanced AI system in production relies on clean, well-structured data pipelines.

When practicing these Pandas patterns, do not simply copy the code. Consider why the data failed, how edge cases are handled, and how your transformations impact the downstream model.

Remain consistent, prioritize mastering patterns over memorizing syntax, and approach your next interview prepared to think like an engineer.

Thank you for reading this article on Python and Pandas problems to practice before an AI/ML interview. For additional insights on AI and machine learning, follow me on Instagram.

Aman Kharwal
Aman Kharwal

AI/ML Engineer | Published Author. My aim is to decode data science for the real world in the most simple words.

Articles: 2231

Leave a Reply

Discover more from AmanXai by Aman Kharwal

Subscribe now to keep reading and get access to the full archive.

Continue reading