12 Prompts for Data Science: Mastering Pandas, Visualization & Analysis

Introduction

If you’ve ever spent 40 minutes debugging a merge() call or Googling “how to rename columns in pandas,” you know the pain. Data science is as much about wrangling data as it is about modeling. The good news: most of those repetitive tasks can be boiled down into reusable “prompts” — structured requests that produce predictable, production-grade code.

In this guide, I’ve compiled twelve prompts I use daily for Pandas, Matplotlib, Seaborn, and Plotly. Each one is presented as a mini case study: the problem it solves, the exact prompt you can type, a working code example, and why it works. By the end, you’ll have a toolbox that saves hours on every project.

How to Use These Prompts

These prompts are designed to be used directly with an AI assistant (like ChatGPT or Claude) or as a reference to write code yourself. If you’re using an AI assistant, paste the prompt and adjust the column/DataFrame names to match your data. If you’re coding solo, the code blocks are fully functional. I’ve chosen libraries that are industry standard — Pandas 2.x, Matplotlib 3.8, Seaborn 0.13, and Plotly Express 5.x.

Overview of the Prompts

# Tool Core Use Case
1 ydata-profiling Automated exploratory data analysis
2 Pandas Missing value imputation with flags
3 Pandas Multi-key merging with suffix handling
4 Pandas Named groupby aggregations
5 Pandas Pivot tables and cross-tabs
6 Pandas Outlier detection with IQR
7 Seaborn + Pandas Correlation heatmap
8 Pandas + Matplotlib Time series resampling & rolling
9 Matplotlib Publication-ready bar charts
10 Seaborn Violin + strip plots for distributions
11 Plotly Express Interactive dashboards
12 Pandas Automated cleaning pipeline

Prompt 1 — Automated Data Profiling

The problem: You just received a brand-new dataset. You don’t know which columns are numeric, which have missing values, or whether there are duplicates. Manual exploration is slow and often incomplete.

The prompt: “Generate a comprehensive data profile report for a pandas DataFrame named df. Identify missing values, data types, cardinality, and potential data quality issues. Suggest appropriate cleaning steps.”

The code:

# Install: pip install ydata-profiling
from ydata_profiling import ProfileReport
import pandas as pd

df = pd.read_csv("sales_data.csv")
profile = ProfileReport(df, title="Sales Data Profiling Report")
profile.to_file("sales_profiling.html")

The result: A standalone HTML report with per-column statistics, missing value matrix, correlations, and highlighted outliers. The prompt directs the model to focus on data quality, so the output goes beyond simple dtypes and gives you actionable insights.

Why it works: It turns a tedious EDA task into a one-liner. According to the official ydata-profiling documentation, the report is designed to “speed up the data analysis process” by automating the most tedious parts. The prompt also asks for suggestions, so you get recommended next steps as well.

Adaptation tip: If your dataset is huge, use df.sample(0.1) to profile a 10% subset first. You’ll get a representative report in a fraction of the time.

Prompt 2 — Intelligent Missing Value Imputation

The problem: Your dataset has missing values in both numeric and categorical columns. dropna() would lose too many rows, and filling with zeros distorts the distribution. You need a context-aware approach that also tracks missingness.

The prompt: “Write pandas code to handle missing values in the 'age' and 'income' columns of DataFrame df. Use median imputation for numeric columns, mode for categorical, and create a flag column indicating whether the value was missing.”

The code:

# Median imputation for age
df['age_imputed'] = df['age'].fillna(df['age'].median())
# Mode for categorical 'education'
df['education_imputed'] = df['education'].fillna(df['education'].mode()[0])
# Flags for missingness
df['age_missing'] = df['age'].isna().astype(int)
df['income_missing'] = df['income'].isna().astype(int)

The result: Separate imputed columns and missing-value flags. The flags let your machine learning model learn from the pattern of missingness—a technique recommended by many Kaggle Grandmasters. The numeric columns are robust to outliers thanks to median, and categorical columns get the most frequent value.

Why it works: The prompt explicitly specifies the imputation strategy and the flag columns. This removes guesswork and follows best practices from the official Pandas documentation on handling missing data.

Adaptation tip: For time-series data, consider method='ffill' (forward fill) instead of median. The prompt can be modified to say “use forward fill” for chronological data.

Prompt 3 — Painless Multi-Key Merging

The problem: You need to join an orders table with a customers table on customer_id. Both have a city column. A naive merge() will silently drop one of the city columns, causing confusion later.

The prompt: “Merge two DataFrames, orders and customers, on the 'customer_id' key using a left join. Handle duplicate column names by adding a '_customer' suffix to non-key columns from the customers table.”

The code:

merged = orders.merge(
    customers,
    on='customer_id',
    how='left',
    suffixes=('_order', '_customer')
)

The result: A clean DataFrame with all order-level data and customer details. orders.city becomes city_order, and customers.city becomes city_customer. This is especially useful when building feature tables for models.

Why it works: The suffixes parameter is a documented feature in the official pandas merge documentation. By mentioning it explicitly, you avoid the silent column-loss problem and make the join traceable.

Adaptation tip: If you expect duplicate keys on either side, add validate='one_to_one' to ensure no accidental duplication. The prompt can be extended: “Validate the merge as one-to-one.”

Prompt 4 — Groupby Aggregations That Actually Read Well

The problem: Using groupby().agg() with a dictionary can produce cryptic column names like ('revenue', 'sum') in a MultiIndex. You need a flat DataFrame with meaningful names.

The prompt: “Use groupby to aggregate sales by region and product category. Calculate total revenue, average discount, and number of transactions. Rename the aggregated columns to 'total_rev', 'avg_discount', 'txn_count'. Output as a clean DataFrame.”

The code:

summary = (df.groupby(['region', 'category'])
             .agg(total_rev=('revenue', 'sum'),
                  avg_discount=('discount', 'mean'),
                  txn_count=('transaction_id', 'count'))
             .reset_index())
print(summary.head())

The result: A tidy DataFrame with these columns: region, category, total_rev, avg_discount, txn_count. No MultiIndex confusion. This is exactly what you want to feed into a bar chart or a pivot table.

Why it works: Named aggregation is a Pandas feature introduced in version 0.25, and it’s the clearest way to do multiple aggregations. The prompt spells out the new column names, so the output is predictable and self-documenting.

Adaptation tip: Use as_index=False in groupby() instead of reset_index() to keep the output flat from the start. You can modify the prompt to say “set as_index=False.”

Prompt 5 — Pivot Tables and Cross-Tabs for Insight

The problem: You have monthly revenue data and want to identify which categories drive growth by quarter—but you need a matrix view.

The prompt: “Create a pivot table showing average monthly sales per product category. Rows = category, columns = month, values = average revenue. Fill missing values with 0. Round to 2 decimals.”

The code:

pivot = pd.pivot_table(df,
                       values='revenue',
                       index='category',
                       columns='month',
                       aggfunc='mean',
                       fill_value=0).round(2)
print(pivot)

The result: A matrix with categories as rows and months as columns. Missing combinations become 0 instead of NaN, which is often better for analysis. This output is directly compatible with Seaborn’s heatmap() for a quick visual.

Why it works: pd.pivot_table() is documented in the official pandas user guide as the go-to tool for spreadsheet-style summaries. The prompt specifies all parameters, removing any ambiguity.

Adaptation tip: Add margins=True to get row/column totals. The prompt can be extended: “Include margins with totals.”

Prompt 6 — Outlier Detection with the IQR Method

The problem: Your price column has extreme values that skew the mean and break charts. You need to identify them and also create a capped version.

The prompt: “Detect outliers in the 'price' column using the IQR method. Create a boolean column 'is_outlier'. Then clip the price values to 1.5x IQR bounds.”

The code:

Q1 = df['price'].quantile(0.25)
Q3 = df['price'].quantile(0.75)
IQR = Q3 - Q1
lower = Q1 - 1.5 * IQR
upper = Q3 + 1.5 * IQR
df['is_outlier'] = (df['price'] < lower) | (df['price'] > upper)
df['price_clipped'] = df['price'].clip(lower, upper)

The result: A boolean flag for outliers and a clipped version of the price column. The IQR rule is the standard Tukey method, making it defensible in a business context.

Why it works: The prompt names the exact method (IQR) and the multiplier (1.5), which are consistent with how the Tukey method is described in statistics textbooks and the pandas clip() documentation.

Adaptation tip: Instead of clipping, you can replace outliers with the median using np.where. Modify the prompt: “Replace outliers with the column median.”

Prompt 7 — Correlation Analysis with a Heatmap

The problem: You have 20 numeric features and want to quickly see which are correlated to make feature-selection decisions.

The prompt: “Compute the Pearson correlation matrix for all numeric columns in df. Visualize it as a heatmap using Seaborn with annotations, a 'coolwarm' colormap, and values from -1 to 1.”

The code:

import seaborn as sns
import matplotlib.pyplot as plt

corr = df.select_dtypes(include='number').corr(method='pearson')
plt.figure(figsize=(10, 8))
sns.heatmap(corr, annot=True, cmap='coolwarm',
            vmin=-1, vmax=1, linewidths=0.5)
plt.title("Feature Correlation Heatmap")
plt.tight_layout()
plt.show()

The result: An annotated heatmap that immediately shows high correlations (red for +1, blue for -1). This helps you catch multicollinearity before building regression models.

Why it works: The prompt specifies the correlation method, color map, annotation, and value limits. These are all parameters that control how the heatmap communicates information.

Adaptation tip: For large feature sets, omit annot=True to avoid overlapping text. The prompt could say “without annotations” if you have more than 10 features.

Prompt 8 — Time Series Resampling and Rolling Statistics

The problem: Your data is collected daily, but you need a weekly trend and a 4-week moving average to present to stakeholders.

The prompt: “Resample daily revenue data to weekly totals using 'W-MON' frequency. Then calculate a 4-week rolling average. Plot both on the same chart.”

The code:

df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
weekly = df['revenue'].resample('W-MON').sum()
rolling = weekly.rolling(4).mean()
plt.plot(weekly.index, weekly, label='Weekly Revenue')
plt.plot(rolling.index, rolling, label='4-Week Rolling Avg', color='red')
plt.legend()
plt.show()

The result: A chart with weekly bars (or line) and a smooth rolling average. The W-MON anchor means each week starts on Monday, which is the convention in many business calendars.

Why it works: The Pandas docstring for resample() says it’s used to “conveniently resample or re-sample time series.” Specifying the frequency and the aggregation method makes the code correct on the first try.

Adaptation tip: Use rolling(4, min_periods=1).mean() to avoid NaN values for the first few weeks. This is especially useful if you have missing weeks.

Prompt 9 — Publication-Ready Matplotlib Styling

The problem: Default Matplotlib charts look like they came from 2005. You need a chart that can go straight into a slide deck.

The prompt: “Create a bar chart of revenue by category in Matplotlib. Set figure size to (10,6), use the 'seaborn-v0_8-darkgrid' style, add value labels on top of each bar, rotate x-axis labels to 45 degrees, and add a grid.”

The code:

import matplotlib.pyplot as plt

plt.style.use('seaborn-v0_8-darkgrid')
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(categories, revenue)
ax.bar_label(bars, fmt='%.0f', padding=2)
plt.xticks(rotation=45)
plt.grid(axis='y')
plt.tight_layout()
plt.show()

The result: A polished bar chart with value labels, a clean grid, and legible axes. fmt='%.0f' ensures the labels are rounded numbers.

Why it works: The bar_label() function (new in Matplotlib 3.4) is the official way to add labels. The prompt makes sure you use it and also includes style details that matter for presentations.

Adaptation tip: To save a high-resolution version for a report, add fig.savefig('revenue_bar.png', dpi=300) before plt.show(). The prompt can be extended with “save as PNG at 300 DPI.”

Prompt 10 — Statistical Visualization with Seaborn’s Categorical Plots

The problem: A boxplot shows quartiles but hides the actual distribution and sample size. You need a richer picture.

The prompt: “Use Seaborn's catplot to create a violin plot of 'price' split by 'product_type'. Overlay the individual data points with a strip plot, and set the color palette to 'Set2'.”

The code:

sns.violinplot(data=df, x='product_type', y='price',
               palette='Set2', inner=None)
sns.stripplot(data=df, x='product_type', y='price',
              color='black', alpha=0.5)
plt.show()

The result: A violin plot showing the full probability density of each group, with black semi-transparent jittered points showing every observation. This is a standard visualization in peer-reviewed scientific papers.

Why it works: Seaborn’s official gallery includes this exact combination. By specifying both plots, the prompt prevents the common mistake of losing the raw data in the KDE smoothing.

Adaptation tip: To compare two subgroups (e.g., gender), add hue='gender' inside the violin plot. The prompt can be modified: “Split by product_type and hue by gender.”

Prompt 11 — Interactive Dashboard with Plotly Express

The problem: Static charts are fine for analysis, but stakeholders want to hover, zoom, and explore the data on their own.

The prompt: “Create an interactive scatter plot of 'revenue' versus 'marketing_spend', colored by 'region', using Plotly Express. Add a trendline and a title. Output a self-contained HTML file.”

The code:

import plotly.express as px

fig = px.scatter(df, x='marketing_spend', y='revenue',
                 color='region', trendline='ols',
                 title='Revenue vs Marketing Spend')
fig.write_html("revenue_plot.html")

The result: An .html file that can be emailed to any stakeholder. They can hover over points to see exact values, zoom into crowded areas, and view the OLS regression line per region.

Why it works: Plotly Express is the recommended high-level interface in the official Plotly docs. The trendline parameter automatically fits and displays the regression line.

Adaptation tip: Add hover_name='product_type' to show the product name in the hover tooltip. You can include this in the prompt: “set hover_name to 'product_type'.”

Prompt 12 — Automated Data Cleaning and Report Generation

The problem: You have 20 messy CSV files and need to standardize them all. Writing the same cleaning code again and again is a waste of time.

The prompt: “Write a Python function that takes a DataFrame, removes duplicate rows, standardizes column names to snake_case, converts date strings to datetime, and returns a summary report with missing value counts.”

The code:

def clean_report(df):
    df = df.drop_duplicates()
    df.columns = [c.strip().lower().replace(' ', '_') for c in df.columns]
    for col in df.select_dtypes(include='object'):
        try:
            df[col] = pd.to_datetime(df[col])
        except ValueError:
            pass
    return df, df.isnull().sum()

The result: A reusable function that you can apply in a loop over all your files, and it gives you a log of missing values for each one. This is the foundation of a reproducible data pipeline.

Why it works: The prompt defines the exact transformation steps and the return value. Standardizing column names to snake_case is a convention recommended in PEP 8 and by the Python community.

Adaptation tip: To preserve the original data, have the function return a new DataFrame instead of modifying in place. The prompt can be changed to “return both the cleaned and original DataFrames.”

Best Practices for Writing Data Science Prompts

  1. Be specific about the method. Instead of saying “handle missing values,” say “use median imputation.” The more specific you are, the more reliable the output.
  2. Name your output columns. This avoids the pain of renaming later and makes the code self-documenting.
  3. Include the libraries and versions. If you require a modern feature like bar_label(), mention the minimum version.
  4. Use a case-study format. Describe the problem, the prompt, the code, and the result. This helps you remember the context and reuse it.
  5. Test on a small sample. Always try the prompt on df.head(100) before running on the full dataset. This is an implicit part of a good prompt workflow.

Sources and Further Reading

These resources were used to verify the APIs and code patterns in this article. Official documentation is the best place to check for version-specific changes.

Final Thoughts

Prompts are more than just AI queries—they’re mental templates. By internalizing these twelve, you’ll stop worrying about syntax and start focusing on the insights hidden in your data. Try them on your next project, tweak them to your own datasets, and let me know which one saves you the most time. Happy analyzing!

← All posts

Comments