15 Prompts for Data Science: From Pandas to Visualization

Data science is not about memorizing functions—it's about asking the right questions in the right language. Whether you are cleaning a messy CSV, building a predictive model, or designing a dashboard, your ability to craft precise prompts for AI assistants (like ChatGPT or Copilot) can cut your analysis time in half.

In this article, I share 15 battle-tested prompts organized by three levels of expertise: Basic (Pandas wrangling), Intermediate (visualization with Matplotlib and Seaborn), and Advanced (composite analyses). Each prompt includes a real-world problem, the exact prompt text, a code example, and the expected outcome. You can copy-paste these directly into your next notebook.

Why Prompts Matter in Data Science

A well-structured prompt saves you from debugging syntax errors and helps you focus on the analytical logic. According to a 2025 survey by Kaggle, over 40% of data scientists now use AI assistants daily for code generation. However, vague prompts like "analyze this data" yield generic outputs. The prompts below are designed to produce production-ready, commented code that follows best practices (e.g., using query() instead of boolean indexing, setting inplace=False, and chaining methods).

Basic Prompts: Pandas Data Wrangling

1. Automate Missing Value Imputation

Problem: You have a DataFrame with missing values in numeric and categorical columns. You need a strategy that imputes medians for numbers and modes for categories, without hardcoding column names.

Prompt:

"Write a Pandas function that takes a DataFrame, identifies numeric and categorical columns (dtype 'object'), and imputes missing values with the median for numeric columns and the mode for categorical columns. Return the imputed DataFrame and a dictionary of imputation values used. Use method chaining and avoid SettingWithCopyWarning."

Code Example:

import pandas as pd
import numpy as np

def smart_impute(df):
    impute_dict = {}
    for col in df.columns:
        if df[col].dtype == 'object':
            mode_val = df[col].mode()[0]
            df[col] = df[col].fillna(mode_val)
            impute_dict[col] = mode_val
        elif df[col].dtype in ['int64', 'float64']:
            med_val = df[col].median()
            df[col] = df[col].fillna(med_val)
            impute_dict[col] = med_val
    return df, impute_dict

Result: A reusable function that handles mixed-type DataFrames without manual column selection.

2. Filter Rows with Complex Conditions

Problem: You need to filter a sales DataFrame for rows where revenue > 1000 AND region is either 'North' or 'East', but you want to use the efficient query() method.

Prompt:

"Using Pandas query(), filter a DataFrame called sales where the column 'revenue' is greater than 1000 and the column 'region' is either 'North' or 'East'. Write the query string using @ for variables if needed. Show both the query and the equivalent boolean indexing."

Code Example:

filtered = sales.query("revenue > 1000 and region in ['North', 'East']")
# Equivalent boolean indexing:
filtered2 = sales[(sales['revenue'] > 1000) & (sales['region'].isin(['North', 'East']))]

Result: Clean, readable, and faster filtering (especially on large datasets).

3. Grouped Aggregations with Multiple Metrics

Problem: You want to compute mean, median, count, and standard deviation of 'amount' grouped by 'category', and sort results by mean descending.

Prompt:

"Write a Pandas chain that groups the DataFrame df by 'category', aggregates the 'amount' column with mean, median, count, and std, then sorts by mean in descending order. Use agg() with a dictionary or a list of named aggregations."

Code Example:

result = (df.groupby('category')['amount']
          .agg(['mean', 'median', 'count', 'std'])
          .sort_values('mean', ascending=False))

Result: A summary table ideal for reporting.

4. Detect and Remove Duplicates

Problem: Your dataset has duplicate rows based on a subset of columns (e.g., 'user_id' and 'date'). You need to keep the first occurrence and log how many duplicates were removed.

Prompt:

"Write code that finds duplicate rows in df based on columns ['user_id', 'date'], counts them, drops duplicates keeping the first, and prints the number of duplicates removed. Use duplicated() and drop_duplicates()."

Code Example:

before = len(df)
df_clean = df.drop_duplicates(subset=['user_id', 'date'], keep='first')
removed = before - len(df_clean)
print(f"Removed {removed} duplicate rows.")

Result: Clean data with a clear audit trail.

5. Reshape Data with Pivot and Melt

Problem: You have a DataFrame in long format (one row per date & city) and need to pivot it into wide format (one column per city, rows by date).

Prompt:

"Using pivot_table(), reshape a DataFrame df with columns ['date', 'city', 'sales'] into a table where rows are unique dates, columns are unique cities, and values are sales sums. Fill missing values with zero. Then demonstrate the reverse operation with melt()."

Code Example:

wide = df.pivot_table(index='date', columns='city', values='sales', aggfunc='sum', fill_value=0)
long = wide.melt(var_name='city', value_name='sales', ignore_index=False).reset_index()

Result: Flexible data reshaping for different analytical needs.

Intermediate Prompts: Visualization with Matplotlib and Seaborn

6. Customized Time Series Plot

Problem: You need to plot monthly revenue over two years with a clear trend line, proper date formatting on x-axis, and annotations for peak months.

Prompt:

"Using Matplotlib and Seaborn, create a line plot of monthly revenue over time. Format the x-axis dates as 'YYYY-MM', add a rolling 3-month average trend line, and annotate the top 3 months with their values. Use a clean style (e.g., 'seaborn-v0_8-whitegrid')."

Code Example:

import matplotlib.pyplot as plt
import seaborn as sns

df['date'] = pd.to_datetime(df['date'])
df_monthly = df.resample('M', on='date')['revenue'].sum().reset_index()

plt.figure(figsize=(12,6))
sns.lineplot(data=df_monthly, x='date', y='revenue', label='Monthly Revenue')
df_monthly['rolling'] = df_monthly['revenue'].rolling(3).mean()
sns.lineplot(data=df_monthly, x='date', y='rolling', label='3-Month Avg', linestyle='--')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Result: A publication-ready time series chart.

7. Correlation Heatmap with Annotations

Problem: You have a DataFrame with 10 numeric columns and want to visualize correlations, masking the upper triangle to avoid redundancy.

Prompt:

"Plot a correlation heatmap using Seaborn. Compute the correlation matrix, create a mask for the upper triangle, set the figure size to 10x8, use a diverging color palette ('coolwarm'), and annotate cells with correlation coefficients rounded to 2 decimals."

Code Example:

import numpy as np
corr = df.corr()
mask = np.triu(np.ones_like(corr, dtype=bool))
plt.figure(figsize=(10,8))
sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='coolwarm', center=0)
plt.show()

Result: A clear, non-redundant correlation matrix.

8. Distribution Comparison (Histogram + KDE)

Problem: Compare the distribution of 'price' across three product categories on the same plot with transparency and a legend.

Prompt:

"Using Seaborn's histplot(), overlay three histograms with KDE curves for the 'price' column, grouped by 'category'. Use transparency (alpha=0.5), different colors for each category, and place the legend outside the plot. Also add vertical lines for each category's mean."

Code Example:

plt.figure(figsize=(10,6))
for cat in df['category'].unique():
    subset = df[df['category'] == cat]
    sns.histplot(subset['price'], kde=True, label=cat, alpha=0.5)
    plt.axvline(subset['price'].mean(), linestyle='--', color='gray')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()

Result: A multi-group density comparison.

9. Box Plot with Swarm Overlay

Problem: Visualize the distribution of 'score' across different 'departments', showing both quartiles and individual data points.

Prompt:

"Create a box plot using Seaborn for the 'score' column grouped by 'department'. Overlay a swarm plot (with small point size and transparency) to show individual observations. Set the figure size to 12x6 and rotate x-tick labels 45 degrees."

Code Example:

plt.figure(figsize=(12,6))
sns.boxplot(data=df, x='department', y='score')
sns.swarmplot(data=df, x='department', y='score', color='black', alpha=0.4, size=3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Result: A detailed view of distribution and outliers.

10. Faceted Bar Plot for Category Breakdown

Problem: Show the count of 'status' values for each 'region' in a separate subplot (facet).

Prompt:

"Using Seaborn's catplot() with kind='count', create a faceted bar plot where each facet represents a 'region', and bars show counts of 'status'. Use the same y-axis scale for all facets and add a title for each facet."

Code Example:

g = sns.catplot(data=df, x='status', col='region', kind='count', sharey=True)
g.set_titles("Region: {col_name}")
plt.show()

Result: A multi-panel comparison ideal for presentations.

Advanced Prompts: Composite Analyses

11. Automated EDA Report Generator

Problem: You need a function that takes a DataFrame and prints a summary report: shape, data types, missing percentages, basic statistics for numeric columns, and value counts for categorical columns with more than 10 unique values.

Prompt:

"Write a Python function eda_report(df) that prints:
- Shape
- Data types
- % missing per column
- For numeric: mean, median, min, max, std
- For categorical with <=10 unique values: value counts
- For categorical with >10 unique values: just the number of unique values
Format the output with clear section headers."

Code Example:

def eda_report(df):
    print("=== SHAPE ===")
    print(df.shape)
    print("\n=== DATA TYPES ===")
    print(df.dtypes)
    print("\n=== MISSING % ===")
    print(df.isnull().mean() * 100)
    print("\n=== NUMERIC STATS ===")
    print(df.describe())
    print("\n=== CATEGORICAL ===")
    for col in df.select_dtypes(include='object'):
        n_unique = df[col].nunique()
        if n_unique <= 10:
            print(f"\n{col}:\n{df[col].value_counts()}")
        else:
            print(f"\n{col}: {n_unique} unique values")

Result: A one-line call that gives you a complete data overview.

12. Outlier Detection with IQR and Visualization

Problem: Identify and flag outliers in numeric columns using the IQR method, then create a scatter plot highlighting them.

Prompt:

"Write a function that, for a given numeric column, computes Q1, Q3, IQR, lower bound (Q1 - 1.5IQR), and upper bound (Q3 + 1.5IQR). Return a boolean mask for outliers. Then use Matplotlib to create a scatter plot of the column vs index, coloring outliers red."

Code Example:

def detect_outliers_iqr(series):
    Q1 = series.quantile(0.25)
    Q3 = series.quantile(0.75)
    IQR = Q3 - Q1
    lower = Q1 - 1.5 * IQR
    upper = Q3 + 1.5 * IQR
    return (series < lower) | (series > upper)

mask = detect_outliers_iqr(df['price'])
plt.figure(figsize=(10,4))
plt.scatter(df.index, df['price'], c=['red' if m else 'blue' for m in mask], alpha=0.6)
plt.xlabel('Index')
plt.ylabel('Price')
plt.show()

Result: A quick outlier audit tool.

13. Feature Engineering from Date Columns

Problem: You have a 'date' column and need to extract day of week (as string), month, year, and a flag for weekends.

Prompt:

"Given a DataFrame df with a datetime column 'date', create new columns: 'day_of_week' (Monday=0, Sunday=6), 'month_name' (string), 'year', and 'is_weekend' (True if day_of_week >= 5). Use vectorized .dt accessor."

Code Example:

df['date'] = pd.to_datetime(df['date'])
df['day_of_week'] = df['date'].dt.dayofweek
df['month_name'] = df['date'].dt.month_name()
df['year'] = df['date'].dt.year
df['is_weekend'] = df['day_of_week'] >= 5

Result: Ready-to-use features for time-series modeling.

14. Custom Aggregation for Cohort Analysis

Problem: You have user activity data with 'user_id', 'date', and 'revenue'. You need to compute monthly retention: for each cohort (users who joined in a given month), show the percentage that made a purchase in subsequent months.

Prompt:

"Write a Pandas script that:
1. Creates a cohort column based on the first purchase month per user (min date).
2. Creates a period number for each subsequent purchase (0 = first month, 1 = next month, etc.).
3. Pivots to show cohort size and retention percentage for periods 0 to 6.
Use groupby and pivot_table."

Code Example:

# Step 1: first purchase month per user
first_month = df.groupby('user_id')['date'].min().dt.to_period('M').rename('cohort')
df = df.join(first_month, on='user_id')
# Step 2: period number
df['period'] = (df['date'].dt.to_period('M') - df['cohort']).apply(lambda x: x.n)
# Step 3: retention
cohort_data = df.groupby(['cohort', 'period'])['user_id'].nunique().reset_index()
cohort_pivot = cohort_data.pivot_table(index='cohort', columns='period', values='user_id')
retention = cohort_pivot.divide(cohort_pivot[0], axis=0) * 100

Result: A classic retention matrix.

15. Multi-Plot Dashboard with Subplots

Problem: Create a single figure with four panels: top-left (histogram), top-right (box plot), bottom-left (line plot), bottom-right (bar plot), with shared x-axis where appropriate.

Prompt:

"Using Matplotlib's subplots() with a 2x2 grid, create a dashboard:
- (0,0): Histogram of 'price' with 30 bins.
- (0,1): Box plot of 'price' by 'category'.
- (1,0): Line plot of 'date' vs 'sales' (aggregated monthly).
- (1,1): Bar plot of average 'rating' per 'category'.
Set a common figure title 'Sales Dashboard' and adjust layout with tight_layout()."

Code Example:

fig, axes = plt.subplots(2, 2, figsize=(14,10))
fig.suptitle('Sales Dashboard', fontsize=16)

# Histogram
axes[0,0].hist(df['price'], bins=30, edgecolor='black')
axes[0,0].set_title('Price Distribution')

# Box plot
sns.boxplot(data=df, x='category', y='price', ax=axes[0,1])
axes[0,1].set_title('Price by Category')

# Line plot (monthly sales)
df_monthly = df.resample('M', on='date')['sales'].sum()
axes[1,0].plot(df_monthly.index, df_monthly.values)
axes[1,0].set_title('Monthly Sales')

# Bar plot
avg_rating = df.groupby('category')['rating'].mean()
axes[1,1].bar(avg_rating.index, avg_rating.values)
axes[1,1].set_title('Average Rating by Category')

plt.tight_layout()
plt.show()

Result: A comprehensive single-figure dashboard.

Conclusion

These 15 prompts are designed to accelerate your daily data science workflow—from cleaning raw data with Pandas to producing publication-quality visualizations. The key is to be specific: mention the function names, the output format, and any constraints (like handling missing values or avoiding warnings). As you practice, you will develop your own library of prompts that reflect your unique analysis patterns.

Next steps: Pick one prompt from each category and apply it to a real dataset—try the NYC Taxi Trips dataset (available on Kaggle) or your own CSV. Modify the prompt parameters and observe how the output changes. Over time, you will learn to anticipate what the AI will generate and how to steer it toward the most efficient solution.

Remember: the best prompt is the one that produces code you can run immediately. Save your favorites in a text file or a Jupyter notebook. Happy analyzing!

← All posts

Comments