20 Essential Prompts for Data Science: Pandas, Analysis & Visualization

20 Essential Prompts for Data Science: Pandas, Analysis & Visualization

Data science is not just about writing code—it's about asking the right questions. In 2026, the most productive data scientists use AI assistants to accelerate their workflow, from exploratory data analysis (EDA) to building predictive models. But a generic "analyze this dataset" rarely yields useful results. The secret lies in prompt engineering for data science.

This article provides 20 specific, copy-paste-ready prompts for data analysis, visualization with Matplotlib and Seaborn, and Pandas operations. Each prompt includes a clear task description and a practical usage example. Whether you're a junior analyst or a senior machine learning engineer, these prompts will save you hours of manual work.

Why Prompt Engineering Matters for Data Science

Modern AI assistants (like GPT-4, Claude, and specialized data science copilots) can generate code, interpret statistics, and suggest visualizations—but only if you give them precise instructions. A vague prompt like "show me the data" produces vague results. A structured prompt with context, output format, and constraints produces production-ready code.

According to a 2025 survey by Kaggle, 73% of data scientists now use AI tools for code generation, but only 28% report high satisfaction with the results. The gap comes from poor prompting. This article closes that gap.

Prompts for Pandas: Data Wrangling & Transformation

Pandas remains the backbone of data manipulation in Python. These prompts cover common tasks: loading, cleaning, merging, and feature engineering.

1. Initial Data Inspection

Task: Quickly understand the structure and quality of a new dataset.

Prompt:

I have a dataset loaded in a Pandas DataFrame called `df`. Generate a comprehensive data inspection report that includes:
- Shape and column data types
- Missing value counts and percentages
- Unique value counts for categorical columns
- Basic descriptive statistics for numerical columns (mean, median, std, min, max, quartiles)
- The first 3 and last 3 rows
Output the report as a formatted text summary. Do not use external libraries beyond Pandas.

Usage Example:

# After loading your data
df = pd.read_csv('sales_data.csv')
# Run the prompt in your AI assistant
# The assistant returns a structured summary you can paste into your notebook or report.

2. Automated Missing Value Handling

Task: Generate a strategy to handle missing values based on column type and distribution.

Prompt:

Given a Pandas DataFrame `df`, write a function `auto_impute(df)` that:
- For numerical columns with <5% missing: fill with median
- For numerical columns with >=5% missing: fill using forward fill (method='ffill')
- For categorical columns with <5% missing: fill with mode
- For categorical columns with >=5% missing: create a new category "Unknown"
- Return the imputed DataFrame and a log of all changes
Use only Pandas. Document the function with a docstring.

Usage Example:

# Apply to your data
cleaned_df, log = auto_impute(df)
print(log)  # See what was changed

3. Feature Engineering from Date Columns

Task: Extract useful features from datetime data.

Prompt:

The DataFrame `df` has a column 'date' of type datetime64. Write code to create these new features:
- day_of_week (Monday=0, Sunday=6)
- is_weekend (boolean)
- month
- quarter
- day_of_year
- week_of_year
- is_month_start, is_month_end
- days_since_last_record (difference from previous row in days, NaN for first row)
Add them to the original DataFrame. Use vectorized Pandas operations only (no loops).

Usage Example:

# Assuming df already has a 'date' column
df['date'] = pd.to_datetime(df['date'])
# Run the prompt to get the feature engineering code

4. Grouped Aggregation with Multiple Metrics

Task: Create a summary table grouped by categories with custom aggregations.

Prompt:

I have a DataFrame `df` with columns: 'category', 'sales', 'quantity', 'profit', 'region'. 
Write code to group by 'category' and 'region' and calculate:
- Total sales, average quantity, median profit
- Count of transactions
- Standard deviation of sales
- Min and max of profit
- The most common category within each group (use lambda)
Output the result as a clean DataFrame with multi-level columns. Sort by total sales descending.

Usage Example:

summary = df.groupby(['category', 'region']).agg(...)
summary.sort_values(('sales', 'total'), ascending=False)

5. Detecting and Handling Outliers

Task: Identify outliers using IQR and cap them.

Prompt:

Write a function `cap_outliers(df, columns, method='iqr', multiplier=1.5)` that:
- For each specified column, calculates Q1, Q3, and IQR
- Identifies outliers as values below Q1 - multiplier*IQR or above Q3 + multiplier*IQR
- Caps outliers to the nearest non-outlier boundary
- Returns the capped DataFrame and a dictionary with outlier count per column
Use only Pandas and NumPy. Handle the case where all values are identical (IQR=0).

Usage Example:

capped_df, outlier_report = cap_outliers(df, ['age', 'income'], multiplier=2.0)
print(outlier_report)

Prompts for Data Visualization with Matplotlib & Seaborn

Visualization is the most common task where prompt engineering shines. Instead of hunting through documentation, let the AI generate the exact plot you need.

6. Automatic Distribution Plot for All Numerical Columns

Task: Generate a grid of histograms for numerical columns.

Prompt:

I have a DataFrame `df` with 12 numerical columns. Write Matplotlib code to create a 4x3 grid of histograms (one per column) with:
- 20 bins each
- Kernel density estimate overlay (using Seaborn's kdeplot)
- Column name as title for each subplot
- Shared x-axis within each row
- Figure size: 16x12 inches
- Tight layout
Use Seaborn for KDE overlay and Matplotlib for the rest.

Usage Example:

# The AI generates the complete plotting code
# You just copy-paste into your notebook

7. Correlation Heatmap with Annotations

Task: Visualize feature correlations clearly.

Prompt:

Create a correlation heatmap for all numerical columns in `df` using Seaborn. Requirements:
- Colormap: 'coolwarm' centered at 0
- Annotate each cell with correlation coefficient rounded to 2 decimals
- Font size for annotations: 8
- Figure size: proportional to number of columns (e.g., 10x8 for 10 columns)
- Mask the upper triangle to avoid redundancy
- Add the title 'Feature Correlation Matrix'
- Rotate x and y labels 45 degrees

Usage Example:

# Run the prompt to get the heatmap code
# This is especially useful before feature selection

8. Time Series Line Plot with Moving Averages

Task: Plot a time series with trend lines.

Prompt:

The DataFrame `df` has columns: 'date' (datetime) and 'value' (float). Write Matplotlib code to create a time series plot with:
- Original data as a thin gray line (alpha=0.5)
- 7-day rolling average as a thick blue line
- 30-day rolling average as a dashed red line
- Shaded area between the rolling averages (alpha=0.1)
- Date on x-axis with monthly ticks and rotated labels
- Grid on y-axis only
- Title: 'Time Series with Moving Averages'
- Use Seaborn style 'darkgrid'

Usage Example:

# Perfect for sales data, website traffic, or sensor readings

9. Comparative Box Plots Across Categories

Task: Compare distributions across groups.

Prompt:

I want to compare the distribution of 'sales' across different 'region' categories. Create a Seaborn box plot with:
- X-axis: 'region' sorted by median sales descending
- Y-axis: 'sales'
- Add swarm plot overlay (small points) with alpha=0.3
- Color the boxes by region using a palette
- Remove top and right spines
- Add a horizontal line at the overall median sales value (dashed, red)
- Title: 'Sales Distribution by Region'

Usage Example:

# Reveals outliers and distribution shape per category

10. Automated Pair Plot for a Subset of Columns

Task: Quickly explore pairwise relationships.

Prompt:

Select 5 numerical columns from `df` that have the highest variance. Create a Seaborn pair plot for these columns with:
- Diagonal: KDE plots
- Off-diagonal: scatter plots with low alpha (0.4)
- Color points by the categorical column 'segment'
- Legend outside the plot
- Figure size: auto-calculated (3 inches per column)
- Title: 'Pairwise Relationships (Top 5 by Variance)'

Usage Example:

# Identifies clusters, correlations, and non-linear relationships quickly

Prompts for Comprehensive Data Analysis Reports

These prompts generate end-to-end analysis, not just code snippets.

11. Automated EDA Report Template

Task: Generate a complete exploratory data analysis report.

Prompt:

I have a DataFrame `df` with 20 columns (mix of numerical and categorical). Write a Python script that produces a complete EDA report as a Markdown string, including:
1. Dataset overview: shape, memory usage, column list with types
2. Missing value analysis: table with counts and percentages, visual bar chart
3. Univariate analysis: histograms for numerical, bar charts for categorical (top 10 categories)
4. Bivariate analysis: correlation heatmap, top 5 strongest correlations explained
5. Outlier detection: columns with outliers (IQR method), count per column
6. Key insights summary: 3-5 bullet points
Save the report as 'eda_report.md' and all figures as PNG files in a 'figures' folder.

Usage Example:

# Run once to get a reusable EDA pipeline for any dataset

12. Data Quality Report Generator

Task: Identify and document data quality issues.

Prompt:

Generate a data quality report for `df` that checks:
- Duplicate rows (exact and near-duplicates with 90% similarity)
- Inconsistent categorical values (e.g., 'Yes', 'yes', 'Y')
- Out-of-range numerical values (negative ages, future dates)
- Skewness for numerical columns (report if >1 or <-1)
- Cardinality for categorical columns (report if >50 unique values)
Output as a structured JSON with issue type, column, severity (high/medium/low), and suggested fix.

Usage Example:

# Automate data validation before model training

13. Statistical Hypothesis Testing

Task: Automate A/B test analysis.

Prompt:

I have two groups in `df`: 'control' and 'treatment' in the column 'group'. The metric is 'conversion_rate' (continuous). Write code to:
- Check normality for both groups using Shapiro-Wilk test
- If normal: use independent t-test; else use Mann-Whitney U test
- Calculate effect size (Cohen's d for normal, rank-biserial for non-normal)
- Generate a plot: two histograms with KDE overlays, vertical lines at means
- Output a summary with test statistic, p-value, effect size, and interpretation (significant or not at alpha=0.05)

Usage Example:

# Directly applicable to marketing experiments

14. Predictive Feature Selection

Task: Identify the most important features for a target variable.

Prompt:

Given `df` with target column 'target' (binary classification), perform feature selection using:
- Mutual information (from sklearn) for all numerical features
- Chi-squared test for categorical features (after encoding)
- Feature importance from a Random Forest classifier (100 trees)
- Correlation with target for numerical features
Output a ranked table with: feature name, method, score, p-value (if applicable), and recommendation (keep/drop).
Visualize top 10 features using a horizontal bar chart (one color per method).

Usage Example:

# Reduces dimensionality before modeling

Prompts for Advanced Pandas Operations

15. Efficient Memory Optimization

Task: Reduce DataFrame memory usage.

Prompt:

Write a function `optimize_memory(df)` that:
- For numerical columns: downcast int64 to int32/int16/int8 where possible, float64 to float32
- For object columns: convert to category if unique values < 50% of total rows
- For datetime columns: ensure proper datetime64 type
- Log original vs new memory usage (in MB) and percentage reduction
- Return the optimized DataFrame
Use Pandas' .info(memory_usage='deep') for measurement.

Usage Example:

# Can reduce memory by 50-80% on large datasets

16. Complex Multi-Table Join

Task: Merge multiple DataFrames intelligently.

Prompt:

I have three DataFrames: `orders` (order_id, customer_id, date, amount), `customers` (customer_id, name, segment, signup_date), and `returns` (order_id, return_date, reason). Write code to:
- Left join orders with customers on customer_id
- Left join the result with returns on order_id
- For unmatched returns, fill return_date with NaT and reason with 'No Return'
- Create a flag column 'has_returned'
- Create a column 'days_to_return' (return_date - date) where applicable
- Output the final merged DataFrame and a summary of row counts before/after each join

Usage Example:

# Typical e-commerce data consolidation task

17. Rolling Window Operations

Task: Compute rolling statistics with custom windows.

Prompt:

For the time series DataFrame `df` with columns 'date' and 'value', calculate:
- 7-day rolling mean, standard deviation, min, max
- 30-day rolling mean
- Exponential weighted moving average (span=14)
- Rolling correlation with a 14-day window between 'value' and a second column 'indicator'
- Rolling z-score (current value minus rolling mean, divided by rolling std) with 30-day window
Output all as new columns with descriptive names. Handle NaN at the beginning of the series.

Usage Example:

# For financial data or sensor anomaly detection

18. Custom Pivot Table with Aggregation

Task: Create a multi-dimensional summary table.

Prompt:

Create a pivot table from `df` with:
- Index: 'year', 'quarter'
- Columns: 'product_category'
- Values: 'revenue'
- Aggregation: sum, mean, and count (separate value columns)
- Fill missing values with 0
- Add row and column totals (margins=True)
- Sort columns by total revenue descending
- Output as a DataFrame with a clean multi-level index

Usage Example:

# Perfect for business reports and dashboards

19. Text Data Processing Pipeline

Task: Clean and vectorize text columns.

Prompt:

The DataFrame `df` has a column 'review_text'. Write a function `clean_text(text_series)` that:
- Converts to lowercase
- Removes punctuation, numbers, and extra whitespace
- Removes stopwords (use NLTK's English stopwords list)
- Lemmatizes words (use NLTK's WordNetLemmatizer)
- Returns a cleaned Series
Then write code to create a TF-IDF matrix (using sklearn) from the cleaned text, limiting to top 500 features. Add the top 5 TF-IDF terms per document as a new column.

Usage Example:

# For sentiment analysis or topic modeling

20. Automated Reporting to Slack/Email

Task: Send analysis results to stakeholders.

Prompt:

Write a function `send_report(df, report_type='daily')` that:
- Computes key metrics: total sales, average order value, top 5 products, new customers
- Creates a summary plot (bar chart of top products)
- Formats the report as a Markdown string
- Sends the report via SMTP email (use environment variables for credentials)
- Saves a copy locally as 'report_{date}.md'
Use Python's built-in smtplib and email.mime modules. Handle errors gracefully (log to file).

Usage Example:

# Automate end-of-day reporting

Putting It All Together: A Complete Workflow

Here's how you might combine these prompts in a real project:

  1. Load data → Prompt #1 for initial inspection
  2. Clean data → Prompts #2, #5 for missing values and outliers
  3. Feature engineering → Prompt #3 for date features
  4. Visualize → Prompts #6, #7, #9 for distributions, correlations, and group comparisons
  5. Generate report → Prompt #11 for a complete EDA report
  6. Model preparation → Prompt #14 for feature selection

This workflow can cut your analysis time from hours to minutes.

Best Practices for Data Science Prompting

  • Be specific about output format: Always specify whether you want code, text, JSON, or a plot.
  • Provide context about the data: Mention column names, data types, and the problem you're solving.
  • Set constraints: Mention which libraries are allowed (e.g., "use only Pandas, no sklearn").
  • Iterate: Don't expect perfect output on the first try. Refine prompts based on results.
  • Test the generated code: AI assistants can make subtle errors. Always run the code in a safe environment first.

Conclusion

Prompt engineering for data science is not a trend—it's a foundational skill for the modern analyst. The 20 prompts in this article cover the most common data tasks: from cleaning and transformation to visualization and reporting. By using these prompts as templates, you can adapt them to any dataset and any problem.

Remember that the quality of the output depends on the quality of the input. Invest time in crafting precise prompts, and your AI assistant will return production-ready code and insights. Start with one prompt from this list, apply it to your current project, and see the difference immediately.

ASI Biont supports integration with data science tools like Jupyter, Pandas, and visualization libraries through automated pipelines—learn more at asibiont.com/courses.

The future of data science is not about writing more code—it's about writing better prompts. Master this skill, and you'll 10x your productivity.

← All posts

Comments