Using pandas, merge employee_df and department_df on department_id, compute the average salary per department, and sort the result by average salary in descending order.
💡 Model Answer
First, merge the two DataFrames on the common key department_id: merged = employee_df.merge(department_df, on='department_id'). Pandas performs a hash‑join internally, which is O(n+m) and keeps the original order of rows unless you specify sort=True. Next, group by the department name and compute the mean salary: avg_salary = merged.groupby('department_name')['salary'].mean(). This produces a Series where each index is a department name and the value is the average salary. If there are missing salaries, pandas will automatically ignore them in the mean calculation. Finally, sort the Series in descending order: sorted_avg = avg_salary.sort_values(ascending=False). Printing sorted_avg shows the departments ranked by average salary. Complexity-wise, the merge is linear in the total number of rows, the groupby and mean are linear in the number of rows, and the sort is O(k log k) where k is the number of distinct departments. Memory usage is proportional to the size of the merged DataFrame, but pandas optimizes by using categorical types for the department names if they are repeated. This approach is typical in data‑engineering scripts that need to aggregate and rank metrics before exporting to a BI tool.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500