There is a DataFrame 'df' with column 'Gender' and 'Salary'. How to calculate the average of the 'Salary' for each 'Gender' using pivot function?
There is a DataFrame 'df' with column 'Gender' and 'Salary'. How to calculate the average of the 'Salary' for each 'Gender' using pivot function?
Solution
pd.pivot_table(df, values='Salary', index='Gender', aggfunc='mean') groups the rows by each unique 'Gender' (the index), takes the 'Salary' column (the values), and applies the mean to each group (the aggfunc). This gives one average salary per gender.
Option 3: pivot_table has no method argument. The aggregation is set with aggfunc.
Option 4: values and index are swapped, so it would try to average 'Gender' grouped by 'Salary'.
We believe the answer could be Option 2 as well, since df.pivot_table(values='Salary', index='Gender', aggfunc='mean') is the same method called on the DataFrame and gives the identical result. However, NTA's final answer key (after all challenges) says Option 1.
Related questions:
2026: 31 May Shift 1
2025: 21 May Shift 1
2025: 3 June Shift 2
2026: 18 May Shift 2