You’ve just received a dataset with 47 columns, nulls scattered everywhere, and dates in three different formats. Your boss expects insights by end of day. Sound familiar? Data science is 80% data wrangling and 20% actual modeling, but most tutorials skip the boring part. That’s where AI prompts come in. Instead of writing boilerplate code from scratch, you can use a well-crafted prompt to generate clean, reusable Python snippets in seconds. This guide collects 15 practical prompts that cover the entire DS workflow—from data cleaning to deployment—each with a concrete example and the exact output you can expect. Whether you’re a junior analyst or a seasoned ML engineer, these prompts will become your new best friends.
1. The Swiss Army Knife: Universal Data Cleaning Prompt
Prompt:
You are an expert data scientist. Given a pandas DataFrame with the following columns: {column_list}, write a Python script that:
1. Detects and handles missing values (mean/median/mode/impute with a constant, based on data type)
2. Removes duplicate rows
3. Converts all string columns to proper casing and strips whitespace
4. Detects and removes outliers using the IQR method (only for numeric columns)
5. Returns a cleaned DataFrame and a summary report of changes made
Use type hints and docstrings. Output only the code.
Example Output:
def clean_dataframe(df: pd.DataFrame) -> (pd.DataFrame, dict):
# ... full implementation ...
report = {'missing_before': ..., 'missing_after': ..., 'duplicates_removed': ...}
return df_clean, report
Why it works: This prompt gives the model enough context to generate a robust function that you can drop into any project. The key is specifying the output format (code only) and the required features (IQR, imputation) so you don’t get a generic answer.
2. EDA in One Shot: Automatic Exploratory Data Analysis
Prompt:
Perform a comprehensive EDA on the dataset {dataset_name} (located at {file_path}). Generate a Jupyter notebook cell that:
- Prints summary statistics for all numeric columns
- Shows value counts for all categorical columns
- Plots histograms for all numeric columns (share x-axis)
- Plots a correlation matrix heatmap
- Identifies columns with high cardinality (>50 unique values) and suggests whether to drop or bin them
Use seaborn and matplotlib. Output only the code.
Example Output:
import seaborn as sns
import matplotlib.pyplot as plt
# ... code that generates all plots ...
Why it works: This prompt saves you from writing repetitive df.describe(), df['col'].value_counts(), and plt.hist() calls. It also adds a smart suggestion about cardinality, which is a common pitfall in feature engineering.
3. Feature Engineering on Autopilot
Prompt:
I have a DataFrame with columns: {column_list}. Suggest 5 new features that could improve the predictive power of a {model_type} model for predicting {target_column}. For each feature, provide a Python code snippet that creates it. Justify each feature in one sentence.
Example Output:
| Feature Name | Code Snippet | Justification |
|---|---|---|
| day_of_week | df['day_of_week'] = pd.to_datetime(df['date']).dt.dayofweek |
Captures weekly seasonality |
| price_per_sqft | df['price_per_sqft'] = df['price'] / df['sqft'] |
Normalizes price by size |
Why it works: The model specifies the target and model type, so the AI can tailor suggestions to your problem. The table format makes it easy to copy-paste into your notebook.
4. Data Validation with Pydantic
Prompt:
Create a Pydantic model that validates the following data: {field_name: type, ...}. Include custom validators for: {custom_rules}. Raise ValueError with descriptive messages. Output only the code.
Example Output:
from pydantic import BaseModel, validator
class UserInput(BaseModel):
age: int
@validator('age')
def age_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Age must be positive')
return v
Why it works: Pydantic is the gold standard for data validation in Python, and this prompt generates a ready-to-use schema that you can integrate into your API or data pipeline.
5. The Model Training Loop with Hyperparameter Tuning
Prompt:
Write a Python script that trains a {model_name} model using scikit-learn. Include:
- Train/test split (80/20)
- StandardScaler for numeric features
- GridSearchCV or RandomizedSearchCV with 5-fold CV
- Evaluation metrics: accuracy, precision, recall, F1
- Plot ROC curve (if binary classification)
- Print best parameters and test score
Use best practices. Output only the code.
Example Output:
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
# ... full training pipeline ...
Why it works: This prompt encapsulates an entire experiment into a single block, making it easy to replicate and modify. You just replace the model name and data path.
6. Explaining Your Model with SHAP
Prompt:
Given a trained model and a test set, generate a SHAP summary plot and a waterfall plot for a single prediction. Include code to compute SHAP values using a TreeExplainer. Output only the code.
Example Output:
import shap
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)
shap.summary_plot(shap_values, X_test)
shap.waterfall_plot(explainer.expected_value, shap_values[0], X_test.iloc[0])
Why it works: SHAP is the industry standard for model interpretability, and this prompt gives you both global and local explanations in one go.
7. Turning a Jupyter Notebook into a FastAPI App
Prompt:
Convert this Jupyter notebook code into a FastAPI application. The API should:
- Accept input data as JSON
- Return model predictions
- Include a /health endpoint
- Use Pydantic for request/response models
- Load the model from a pickle file
Provide the complete Python file.
Example Output:
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
app = FastAPI()
model = joblib.load('model.pkl')
class InputData(BaseModel):
feature1: float
feature2: float
@app.post('/predict')
def predict(data: InputData):
# ...
return {'prediction': pred}
Why it works: This is a classic transition from research to production, and the prompt handles all the boilerplate (routing, validation) so you can focus on your model.
8. Writing Unit Tests for Your Data Pipeline
Prompt:
Write a pytest test suite for the following functions: {function_name}: {description}. Include tests for edge cases and expected exceptions. Use fixtures where appropriate. Output only the code.
Example Output:
import pytest
from my_module import clean_data
def test_clean_data_removes_duplicates():
df = pd.DataFrame({'a': [1, 1, 2]})
assert len(clean_data(df)) == 2
Why it works: Testing is often skipped due to time pressure. This prompt generates a solid starting point for a test suite, ensuring your pipeline is robust.
9. Containerizing Your ML Model with Docker
Prompt:
Create a Dockerfile for a Python ML service that:
- Uses python:3.9-slim as the base image
- Installs dependencies from requirements.txt
- Copies the application code
- Runs a FastAPI app with uvicorn on port 8000
- Uses a non-root user for security
Include a .dockerignore file.
Example Output:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER 1000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Why it works: Containerization is essential for deployment, and this prompt gives you a secure, minimal Dockerfile that you can build upon.
10. Setting Up CI/CD for Your ML Project
Prompt:
Create a GitHub Actions workflow for an ML project that:
- Triggers on push to main and pull requests
- Runs tests with pytest
- Lints the code with flake8
- Builds a Docker image and pushes it to Docker Hub
- Deploys to a cloud provider (AWS Lambda or Kubernetes) using a placeholder
Include comments explaining each step.
Example Output:
name: CI/CD
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run tests
run: pytest
deploy:
needs: test
# ...
Why it works: This prompt automates the boring parts of deployment, so you can ship models faster and with confidence.
11. Monitoring Your Model in Production
Prompt:
Write a Python script that monitors a deployed ML model by:
- Logging predictions and actuals to a CSV file
- Calculating drift metrics (PSI or KS test) on a weekly basis
- Sending an alert (email or Slack webhook) if drift exceeds a threshold
Use the `scipy.stats.ks_2samp` function for the KS test. Output only the code.
Example Output:
from scipy.stats import ks_2samp
# ...
if ks_stat > 0.1:
send_alert('Model drift detected!')
Why it works: Model monitoring is crucial for maintaining performance, and this prompt gives you a simple yet effective approach.
12. Automating Your Daily Data Report
Prompt:
Create a Python script that generates a daily sales report from a SQL database. The report should:
- Connect to PostgreSQL using SQLAlchemy
- Query total sales, new customers, and top products
- Save the results as a CSV and a Plotly HTML file
- Send the report via email using SMTP
Include error handling and logging.
Example Output:
# ... full script with logging and email sending ...
Why it works: This prompt creates a complete automation script that saves you hours every week.
13. Generating Synthetic Data for Testing
Prompt:
Generate synthetic data for a {domain} dataset with {n} rows and the following columns: {column_list}. The data should mimic real-world distributions (e.g., normal, log-normal, categorical). Use NumPy and Pandas. Output only the code.
Example Output:
import numpy as np
import pandas as pd
data = {'age': np.random.normal(35, 10, 1000), ...}
df = pd.DataFrame(data)
Why it works: Sometimes you need dummy data for testing or demos. This prompt generates realistic-looking data with minimal effort.
14. Explaining Your Model with LIME
Prompt:
Use LIME to explain a prediction from a trained model. Write code that:
- Creates a LimeTabularExplainer with training data
- Explains a single instance from the test set
- Displays the explanation in a Jupyter notebook
Output only the code.
Example Output:
import lime
import lime.lime_tabular
explainer = lime.lime_tabular.LimeTabularExplainer(X_train, feature_names=...)
exp = explainer.explain_instance(X_test[0], model.predict_proba)
exp.show_in_notebook()
Why it works: LIME is another popular interpretability tool, and this prompt gives you a working example in seconds.
15. Documenting Your Data Science Project
Prompt:
Write a README.md for a data science project that includes:
- Project title and description
- Installation instructions
- Usage example (with code)
- Data source citation
- Model performance summary
- License information
Use Markdown and keep it concise.
Example Output:
# My ML Project
## Description
...
## Installation
...
## Usage
...
Why it works: Good documentation is often neglected. This prompt generates a structured README that you can customize.
16. Optimizing Your Python Code with Profiling
Prompt:
Profile the following function using cProfile and line_profiler. Identify bottlenecks and suggest optimizations. Provide the optimized code.
Example Output:
# ... profiled and optimized code ...
Why it works: Performance matters, especially in data pipelines. This prompt helps you pinpoint slow parts and fix them.
17. Creating an API Client for Your Model
Prompt:
Write a Python client that calls a REST API for a deployed ML model. The client should:
- Take input features as arguments
- Send a POST request to {endpoint}
- Handle errors and retries
- Return the prediction
Use `requests` library. Output only the code.
Example Output:
import requests
def predict(features):
response = requests.post('http://api.example.com/predict', json=features)
response.raise_for_status()
return response.json()['prediction']
Why it works: This prompt provides a ready-to-use client that you can integrate into your application.
18. Building a Simple ML Pipeline with Airflow
Prompt:
Create an Apache Airflow DAG that runs a daily ML training pipeline. The DAG should:
- Extract data from a PostgreSQL database
- Preprocess the data
- Train a model
- Save the model to S3
- Trigger a Slack notification on success/failure
Provide the DAG code.
Example Output:
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
# ...
Why it works: Orchestration is key for production ML, and this prompt gives you a starting point for a robust pipeline.
Conclusion
These 18 prompts cover the entire data science lifecycle—from cleaning messy data to deploying and monitoring models. By integrating them into your daily workflow, you can save hours of coding time and focus on the analytical side of your work. Try them out, adapt them to your projects, and watch your productivity soar. Have a favorite prompt? Share it in the comments below!
Comments