JuniorCodeVery commonNot answered yet
Total sales per employee by merging two DataFrames
df_names has columns emp_id, emp_name; df_sales has emp_id, date, num_sales. Produce a DataFrame with each employee's name and their total number of sales across all dates.
import pandas as pd
def total_sales(df_names: pd.DataFrame, df_sales: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
Aggregate sales per employee, then attach the name. Group sales by emp_id and sum num_sales, then merge with the names on emp_id: df_sales.groupby('emp_id')['num_sales'].sum().reset_index().merge(df_names, on='emp_id')[['emp_name','num_sales']].
- ✗Using concat instead of a key-based merge
- ✗Returning per-date rows without summing num_sales
- ✗Counting name rows instead of summing sales
- →Does it matter whether you group before or after the merge?
- →How would an employee with no sales appear?
Sum each employee's sales, then merge in the name on the shared emp_id key.
import pandas as pd
def total_sales(df_names: pd.DataFrame, df_sales: pd.DataFrame) -> pd.DataFrame:
totals = (df_sales.groupby('emp_id')['num_sales']
.sum()
.reset_index())
return totals.merge(df_names, on='emp_id')[['emp_name', 'num_sales']]
Grouping first reduces each employee to one row before the join, so the merge is small. A plain inner merge drops employees with no sales rows; use a right/outer merge with fillna(0) if those should appear with a zero total.