Python for Data Analysts
๐ฅ Pandas Scenario-Based Interview Question ๐ผ
๐ Scenario:
You have an orders dataset with:
order_id
customer_id
order_date
category
sales
๐ฏ Task:
Find the top-selling category for each month based on total sales.
โ
Pandas Solution:
import pandas as pd
# Convert to datetime
df['order_date'] = pd.to_datetime(df['order_date'])
# Extract month
df['month'] = df['order_date'].dt.strftime('%b-%Y')
# Total sales by month & category
sales_summary = (
df.groupby(['month', 'category'])['sales']
.sum()
.reset_index()
)
# Rank categories within each month
sales_summary['rank'] = (
sales_summary.groupby('month')['sales']
.rank(method='dense', ascending=False)
)
# Top category per month
result = sales_summary[sales_summary['rank'] == 1]
print(result)
๐ก Concepts Tested:
โ๏ธ groupby()
โ๏ธ Date handling
โ๏ธ Aggregation
โ๏ธ Ranking within groups
React โฅ๏ธ for more interview questions
16 ยท 5.6K ยท