12 Prompts for Data Science: Data Analysis, Visualization, and Pandas
Data science is a multidisciplinary field that combines statistics, programming, and domain expertise to extract insights from data. According to the U.S. Bureau of Labor Statistics, employment in data science occupations is projected to grow 36% from 2023 to 2033, much faster than the average for all occupations. For practitioners, tools like Pandas, Matplotlib, and Seaborn are essential for efficient data manipulation and visualization. However, knowing what to ask an AI assistant can be a game-changer: the right prompt can save hours of debugging or exploration. This article provides 12 ready-to-use prompts for data science tasks, each with a real-world example and code snippet. Whether you are cleaning a messy CSV, building a regression plot, or optimizing a Pandas pipeline, these prompts will accelerate your workflow.
1. Data Cleaning with Pandas: Handling Missing Values
Task: Identify and handle missing values in a dataset.
Prompt: "I have a DataFrame df with columns 'age', 'salary', and 'department'. About 10% of 'age' values are NaN, and 'salary' has some outliers. Write Python code using Pandas to: (a) display the count of missing values per column, (b) fill missing 'age' with the median, and (c) clip 'salary' to the 1st and 99th percentiles."
Explanation: This prompt addresses common data quality issues. Missing values can bias analysis if not treated. Using median for age is robust to outliers, while clipping salary prevents extreme values from skewing visualizations.
Example:
import pandas as pd
import numpy as np
# Sample data
df = pd.DataFrame({
'age': [25, np.nan, 30, 45, np.nan, 35],
'salary': [50000, 60000, 1200000, 55000, 48000, 70000],
'department': ['HR', 'IT', 'IT', 'HR', 'IT', 'HR']
})
# a) Missing value count
missing_count = df.isnull().sum()
print("Missing per column:", missing_count)
# b) Fill age with median
df['age'] = df['age'].fillna(df['age'].median())
# c) Clip salary
lower = df['salary'].quantile(0.01)
upper = df['salary'].quantile(0.99)
df['salary'] = df['salary'].clip(lower, upper)
print(df)
2. Exploratory Data Analysis (EDA) Summary Statistics
Task: Generate descriptive statistics and check data types.
Prompt: "Using Pandas, write code to get a full EDA summary for a DataFrame df: (a) data types and non-null counts using .info(), (b) descriptive statistics for numeric columns with .describe(), and (c) frequency count for a categorical column 'product_type'. Explain each output."
Explanation: EDA is the first step in any data science project. .info() reveals memory usage and missing values; .describe() shows central tendency and dispersion; frequency tables help understand category distribution.
Example:
# Assume df is loaded
print(df.info())
print(df.describe())
print(df['product_type'].value_counts())
This code quickly surfaces data shape, numeric summaries, and category imbalance.
3. Data Visualization with Matplotlib: Line Plot for Time Series
Task: Plot a time series trend.
Prompt: "I have a time series DataFrame with columns 'date' (datetime) and 'sales' (float). Write Matplotlib code to create a line plot with: (a) date on x-axis, sales on y-axis, (b) a title 'Monthly Sales Trend', (c) grid lines, and (d) rotating x-tick labels for readability."
Explanation: Time series visualization is critical for trend analysis. Rotating labels prevents overlap. Grid lines improve readability.
Example:
import matplotlib.pyplot as plt
import pandas as pd
# Sample data
df = pd.DataFrame({
'date': pd.date_range('2025-01-01', periods=12, freq='M'),
'sales': [200, 210, 250, 240, 300, 310, 280, 290, 350, 340, 360, 400]
})
plt.figure(figsize=(10,5))
plt.plot(df['date'], df['sales'], marker='o')
plt.title('Monthly Sales Trend')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
4. Statistical Visualization with Seaborn: Correlation Heatmap
Task: Visualize correlations between numeric variables.
Prompt: "For a DataFrame with columns 'age', 'income', 'spending_score', and 'tenure', write Seaborn code to create a heatmap of the Pearson correlation matrix. Include annotations and use a 'coolwarm' colormap. Set the figure size to 8x6."
Explanation: Correlation heatmaps reveal linear relationships. Seaborn's heatmap with annotations makes patterns immediately visible. The 'coolwarm' colormap is diverging, highlighting positive (red) and negative (blue) correlations.
Example:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Sample data
df = pd.DataFrame({
'age': [25, 30, 35, 40, 45],
'income': [50000, 60000, 70000, 80000, 90000],
'spending_score': [30, 50, 70, 40, 60],
'tenure': [1, 2, 3, 4, 5]
})
plt.figure(figsize=(8,6))
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('Correlation Heatmap')
plt.show()
5. GroupBy Operations: Aggregating by Category
Task: Compute grouped statistics.
Prompt: "My DataFrame sales_df has columns 'region', 'product', 'revenue', and 'quantity'. Write Pandas code to: (a) group by 'region' and calculate total revenue and average quantity, (b) group by both 'region' and 'product' and find the max revenue, and (c) reset the index for readability."
Explanation: GroupBy is a cornerstone of data aggregation. This prompt covers single and multi-level grouping, and resetting index for clean output.
Example:
# Sample data
df = pd.DataFrame({
'region': ['North', 'North', 'South', 'South', 'East'],
'product': ['A', 'B', 'A', 'B', 'A'],
'revenue': [100, 150, 200, 250, 300],
'quantity': [10, 15, 20, 25, 30]
})
# a)
region_stats = df.groupby('region').agg({'revenue': 'sum', 'quantity': 'mean'})
print(region_stats)
# b)
region_product_max = df.groupby(['region', 'product'])['revenue'].max().reset_index()
print(region_product_max)
6. Feature Engineering: Creating New Columns
Task: Derive new features from existing data.
Prompt: "I have a DataFrame with columns 'purchase_date' (datetime) and 'amount'. Write Pandas code to create: (a) a 'month' column from purchase_date, (b) a 'log_amount' column using numpy log, and (c) a 'is_weekend' boolean column based on purchase_date day of week."
Explanation: Feature engineering improves model performance. Month captures seasonality, log transform normalizes skewed distributions, and weekend flag captures behavioral patterns.
Example:
import pandas as pd
import numpy as np
# Sample data
df = pd.DataFrame({
'purchase_date': pd.date_range('2025-06-01', periods=10, freq='D'),
'amount': [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
})
df['month'] = df['purchase_date'].dt.month
df['log_amount'] = np.log(df['amount'])
df['is_weekend'] = df['purchase_date'].dt.dayofweek >= 5
print(df)
7. Merging and Joining DataFrames
Task: Combine two datasets on a common key.
Prompt: "I have two DataFrames: customers (columns: customer_id, name, age) and orders (columns: order_id, customer_id, amount). Write Pandas code to perform an inner join on customer_id, then group by name to get total amount per customer. Show the resulting DataFrame."
Explanation: Merging is essential for relational data. Inner join keeps only matching records; then aggregation summarizes customer behavior.
Example:
customers = pd.DataFrame({
'customer_id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35]
})
orders = pd.DataFrame({
'order_id': [101, 102, 103, 104],
'customer_id': [1, 2, 1, 3],
'amount': [50, 100, 75, 120]
})
merged = pd.merge(customers, orders, on='customer_id', how='inner')
result = merged.groupby('name')['amount'].sum().reset_index()
print(result)
8. Handling Outliers with IQR Method
Task: Detect and remove outliers using the Interquartile Range (IQR) method.
Prompt: "For a numeric column 'price' in DataFrame df, write Python code to: (a) calculate Q1, Q3, and IQR, (b) define lower and upper bounds as Q1 - 1.5IQR and Q3 + 1.5IQR, (c) filter out rows where price is outside these bounds, and (d) print the number of rows removed."
Explanation: IQR is a standard non-parametric method for outlier detection. It works well for skewed distributions.
Example:
# Sample data
df = pd.DataFrame({'price': [10, 12, 15, 18, 20, 100, 22, 25, 30]})
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
initial_count = len(df)
df_clean = df[(df['price'] >= lower) & (df['price'] <= upper)]
removed = initial_count - len(df_clean)
print(f"Removed {removed} outliers")
9. Customizing Matplotlib: Multiple Subplots
Task: Create a 2x2 grid of plots for different variables.
Prompt: "Write Matplotlib code to create a 2x2 subplot grid for DataFrame df with columns 'age', 'income', 'spending', and 'tenure'. Plot histograms for each column with 20 bins. Add a main title 'Distribution of Customer Features' and adjust spacing."
Explanation: Subplots allow side-by-side comparison of distributions, essential for understanding feature spread.
Example:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Sample data
np.random.seed(0)
df = pd.DataFrame({
'age': np.random.normal(40, 10, 100),
'income': np.random.normal(60000, 15000, 100),
'spending': np.random.normal(50, 20, 100),
'tenure': np.random.normal(3, 1, 100)
})
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
columns = ['age', 'income', 'spending', 'tenure']
for ax, col in zip(axes.flatten(), columns):
ax.hist(df[col], bins=20, edgecolor='black')
ax.set_title(col)
plt.suptitle('Distribution of Customer Features')
plt.tight_layout()
plt.show()
10. Pivot Tables with Pandas
Task: Create a pivot table to summarize data.
Prompt: "I have a DataFrame with columns 'year', 'quarter', 'product', and 'sales'. Write Pandas code to create a pivot table with year as rows, quarter as columns, and sum of sales as values. Fill missing values with 0."
Explanation: Pivot tables are powerful for cross-tabulation, revealing patterns across categories.
Example:
df = pd.DataFrame({
'year': [2024, 2024, 2025, 2025, 2024],
'quarter': ['Q1', 'Q2', 'Q1', 'Q2', 'Q3'],
'product': ['A', 'A', 'B', 'B', 'A'],
'sales': [100, 150, 200, 250, 300]
})
pivot = df.pivot_table(values='sales', index='year', columns='quarter', aggfunc='sum', fill_value=0)
print(pivot)
11. Applying Functions with apply() and lambda
Task: Transform a column using a custom function.
Prompt: "I have a DataFrame with a column 'email'. Write Pandas code using apply and a lambda function to extract the domain part (everything after '@') into a new column 'domain'. Handle cases where email is missing (NaN) by filling with 'unknown'."
Explanation: The apply method is versatile for row-wise operations. Lambda functions keep code concise.
Example:
df = pd.DataFrame({'email': ['alice@example.com', 'bob@test.org', None, 'charlie@domain.net']})
df['domain'] = df['email'].apply(lambda x: x.split('@')[1] if pd.notna(x) else 'unknown')
print(df)
12. Saving and Loading Data Efficiently
Task: Save a processed DataFrame to CSV with no index, then reload it.
Prompt: "After cleaning DataFrame df_clean, write Pandas code to: (a) save it to 'clean_data.csv' without the index column, and (b) load it back into a new DataFrame df_loaded. Verify the shape matches."
Explanation: Proper I/O prevents data loss. Saving without index avoids an unwanted column; reloading with index_col=0 is a common mistake to avoid.
Example:
# Save
df_clean.to_csv('clean_data.csv', index=False)
# Load
df_loaded = pd.read_csv('clean_data.csv')
# Verify
print(f"Original shape: {df_clean.shape}, Loaded shape: {df_loaded.shape}")
Conclusion
These 12 prompts cover essential data science tasks: cleaning, EDA, visualization, grouping, merging, feature engineering, and I/O. By using these ready-made prompts with an AI assistant, you can reduce boilerplate coding and focus on analysis. For further learning, refer to the official Pandas documentation (pandas.pydata.org) and Matplotlib gallery (matplotlib.org). Experiment with your own datasets—modify the prompts to match your column names and business questions. Happy data wrangling!
Comments