10 Prompts for Data Science: Pandas, Visualization, and Clean Analysis
Data science is as much about asking the right questions as it is about writing the right code. With AI assistants becoming a standard part of a data professional's toolkit, the quality of your queries—your prompts—determines the quality of the output. A poorly worded prompt can produce vague, broken code, while a well-crafted one can save you hours of debugging.
In this article, I’ve compiled 10 battle-tested prompts that I use regularly for data analysis, visualization, and pandas-heavy workflows. Each prompt comes with a concrete use case, a reusable template, and an example of the kind of output you can expect. Whether you’re a beginner trying to understand pandas or a seasoned analyst looking to accelerate your EDA, these prompts will help you get better results from your AI assistant.
Prompting Basics That Actually Work
Before we jump into the collection, here are three principles that make a data-science prompt effective:
- Context matters: Provide a sample of your data, column names, and the desired output.
- Be explicit about the goal: Don’t say “plot the data”; say “create a bar chart of average revenue by region using seaborn with a light grid.”
- Ask for code + explanation: When you need to understand the “why”, ask the AI to comment each line. This turns a code generator into a mentor.
Quick Overview of the 10 Prompts
| # | Prompt Name | Best Used For |
|---|---|---|
| 1 | Data Cleaning on Autopilot | Messy raw data with missing values and duplicates |
| 2 | One-Shot EDA Report | Initial exploration of a new dataset |
| 3 | Feature Engineering Brainstorm | Creating new features from existing columns |
| 4 | Making Matplotlib Beautiful | Publication-quality charts |
| 5 | Seaborn Pairplot with Style | Visualizing multi-dimensional relationships |
| 6 | Time Series Decomposition | Understanding trend, seasonality, and residual |
| 7 | Reshape with Melting and Pivoting | Converting between wide and long formats |
| 8 | Statistical Testing Made Simple | Running t-tests and correlations |
| 9 | Data Validation Rules | Enforcing data quality before modeling |
| 10 | Automated HTML Report | Sharing results with non-technical stakeholders |
1. Data Cleaning on Autopilot
When to use it: You’ve just received a raw CSV with missing values, duplicate rows, and inconsistent data types. You want a reusable cleaning function that can be applied to any such dataframe.
Template:
I have a pandas DataFrame `df` with columns: {column_names}. Write a Python script that:
1. Reports missing values per column
2. Fills numerical columns with the median and categorical with the mode
3. Removes duplicate rows
4. Converts the `date` column to datetime
5. Prints a before/after summary
Example output:
import pandas as pd
def clean_data(df):
print("Before:", df.shape)
num_cols = df.select_dtypes(include=['number']).columns
df[num_cols] = df[num_cols].fillna(df[num_cols].median())
cat_cols = df.select_dtypes(include=['object']).columns
df[cat_cols] = df[cat_cols].fillna(df[cat_cols].mode().iloc[0])
df = df.drop_duplicates().reset_index(drop=True)
df['date'] = pd.to_datetime(df['date'])
print("After:", df.shape, "Missing total:", df.isnull().sum().sum())
return df
Why it works: The prompt breaks the task into a bulleted list of explicit operations. Adding the specific treatment strategies (median, mode) prevents the model from improvising with a different imputation method.
2. One-Shot EDA Report
When to use it: You need a quick but comprehensive overview of a new dataset to guide your analysis.
Template:
Write a complete EDA script using pandas, matplotlib, and seaborn. It should use a DataFrame `df` with columns {col_names}. The script must generate:
- Descriptive statistics (mean, median, std)
- A missing-values heatmap
- A correlation heatmap
- A 2x2 grid of histograms for numerical columns
- A boxplot for each numerical column
Set a consistent style with seaborn.set_theme(). Save the figures to a directory.
Example output:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid")
print(df.describe())
sns.heatmap(df.isnull(), cbar=False).set_title("Missing values")
plt.show()
sns.heatmap(df.corr(), annot=True, cmap="coolwarm").set_title("Correlation")
plt.show()
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
for col, ax in zip(df.select_dtypes(include=['number']).columns[:4], axes.flat):
df[col].hist(ax=ax)
ax.set_title(col)
plt.tight_layout()
plt.savefig("histograms.png", dpi=150)
Why it works: By specifying exact chart types and a consistent theme, you avoid the generic five-over-one layout the model picks by default.
3. Feature Engineering Brainstorm
When to use it: You have a flat table and want to create new predictors that capture hidden patterns.
Template:
I have a dataset with columns {list}. Suggest 5 new features I can create from these, explain why they might help, and provide pandas code to create them. Assume a target column `target` for prediction.
Example output:
df['revenue_per_user'] = df['revenue'] / df['users']
df['day_of_week'] = df['date'].dt.dayofweek
df['price_segment'] = pd.cut(df['price'], bins=3, labels=['low', 'med', 'high'])
df['monthly_avg'] = df.groupby('month')['value'].transform('mean')
df['prev_week_sales'] = df['sales'].shift(7)
Why it works: The prompt asks for an explanation, which forces the model to ground its suggestions in actual domain logic rather than random transformations.
4. Making Matplotlib Beautiful
When to use it: You need a chart that doesn’t look like it came from 2005. Use this for any report or presentation.
Template:
Create a matplotlib chart for the data in `df` comparing {x} and {y}. Use a clean style (grid, no top/right spines), annotate the maximum value, use a color palette from seaborn, and set figure size to (10,6). Save as PNG at 300 dpi.
Example output:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
fig, ax = plt.subplots(figsize=(10, 6))
ax.spines[['top', 'right']].set_visible(False)
ax.plot(df['x'], df['y'], marker='o', color=sns.color_palette()[0])
max_idx = df['y'].idxmax()
ax.annotate(f"Max: {df['y'].max():.2f}",
xy=(df['x'][max_idx], df['y'][max_idx]),
xytext=(5, 5), textcoords="offset points")
plt.tight_layout()
plt.savefig("chart.png", dpi=300)
Why it works: It gives specific design instructions, which forces the model to follow accepted data-visualization best practices like removing chart clutter.
5. Seaborn Pairplot with Style
When to use it: You want to explore pairwise relationships between many variables in one glance.
Template:
Generate a seaborn pairplot for the numeric columns in `df`, colored by the `target` column. Use alpha=0.6, a custom palette ('viridis' if target is continuous else 'Set1'), and rotate the x-axis labels 45 degrees. Save as a high-res figure.
Example output:
import seaborn as sns
import matplotlib.pyplot as plt
palette = 'viridis' if df['target'].dtype in ['float64', 'int64'] else 'Set1'
sns.pairplot(df, hue='target', palette=palette, alpha=0.6, plot_kws={'s': 20})
plt.xticks(rotation=45)
plt.savefig("pairplot.png", dpi=300)
Why it works: The prompt correctly specifies the palette selection logic and rotation, something the model often gets wrong if left to its own devices.
6. Time Series Decomposition
When to use it: You have a time series and want to understand the underlying trend, seasonality, and noise.
Template:
Decompose this time series `df['value']` using statsmodels. I want to see trend, seasonal, and residual components. The index is daily data. Plot each component using matplotlib and explain what the decomposition tells me.
Example output:
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(df['value'], model='additive', period=365)
result.plot()
plt.show()
Why it works: Asking for an explanation along with the plot yields a human-readable summary, not just a giant matrix of plots.
7. Reshape with Melting and Pivoting
When to use it: Your data is in the wrong shape for the analysis you want to run.
Template:
I have a DataFrame with columns {wide_format} and I want it in long format for analysis. Write pandas code using melt to convert it, and then pivot it back for a report. Show the first two rows of each result.
Example output:
long_df = df.melt(id_vars=['id'], value_vars=['A', 'B'],
var_name='metric', value_name='value')
wide_df = long_df.pivot(index='id', columns='metric', values='value')
print(long_df.head(2))
print(wide_df.head(2))
Why it works: Providing a concrete before/after request eliminates ambiguity and gives you both transformations in one shot.
8. Statistical Testing Made Simple
When to use it: You need to validate a hypothesis or quantify the relationship between variables.
Template:
Using scipy.stats, perform a t-test comparing `group1` and `group2` from columns in `df`. Also calculate Pearson correlation between `x` and `y`. For both, interpret the p-value in the context of the data. Return code and a short interpretation.
Example output:
from scipy import stats
t_stat, p_value = stats.ttest_ind(df['group1'], df['group2'])
corr, corr_p = stats.pearsonr(df['x'], df['y'])
print(f"t-test: stat={t_stat:.3f}, p={p_value:.4f}")
print(f"Correlation: r={corr:.3f}, p={corr_p:.4f}")
if p_value < 0.05:
print("Significant difference between groups")
else:
print("No significant difference found")
Why it works: The prompt explicitly asks for the interpretation, which nudges the model to explain the result in plain language rather than dumping numbers.
9. Data Validation Rules
When to use it: You want to enforce quality checks before feeding data into a model.
Template:
Write a pandas script to validate this DataFrame `df`. Check that:
- No negative values in `sales`
- `age` is between 0 and 120
- `email` contains '@'
- No duplicate `user_id`s
Output a report with pass/fail status for each rule.
Example output:
rules = {
"sales_positive": (df['sales'] >= 0).all(),
"age_range": df['age'].between(0, 120).all(),
"email_format": df['email'].str.contains('@').all(),
"unique_user": df['user_id'].is_unique
}
for rule, passed in rules.items():
print(f"{rule}: {'PASS' if passed else 'FAIL'}")
Why it works: Stating precise rules prevents the AI from inventing its own validations or making assumptions about business logic.
10. Automated HTML Report
When to use it: You need to share insights with non-technical stakeholders quickly.
Template:
Create a Python script that reads `df` and produces an HTML report using pandas `to_html()` and a simple Jinja2 template. The report should show summary stats, a correlation matrix, and a section listing the top 10 rows. Use a Bootstrap CDN for styling.
Example output:
import pandas as pd
from jinja2 import Template
tpl = Template("""
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>{{ title }}</h1>
<h2>Summary</h2>
{{ df_summary }}
<h2>Correlation</h2>
{{ df_corr }}
<h2>Top 10 Rows</h2>
{{ df_head }}
</body>
</html>
""")
html = tpl.render(title="Sales Report",
df_summary=df.describe().to_html(classes='table table-striped'),
df_corr=df.corr().to_html(classes='table table-bordered'),
df_head=df.head(10).to_html(classes='table table-hover'))
open("report.html", "w").write(html)
Why it works: It produces a complete, shareable artifact from a single prompt. The use of Bootstrap makes the report look professional without any extra CSS.
Where to Go Next
These prompts work best when paired with a solid understanding of the underlying libraries. I recommend referencing the official documentation for pandas, matplotlib, and seaborn. You can also check out OpenAI’s prompt engineering guide for general techniques on structuring complex tasks.
Remember to always review generated code before using it in production. AI is a tool that amplifies your intent, so the clearer you are about what you need, the better it serves you.
If you found these prompts useful, try them on your next dataset and see the difference. Have a favorite prompt that I missed? Reach out—I’m always looking to expand my own toolkit.
Comments