Exercise · NumPy and pandas · lesson 12 of 12
Exercise: median per group
Write a function group_medians(df, by, column): it groups the rows of the table df by the column by and returns a dictionary. A key of the dictionary is a value from by, and its value is the median of the column column in that group.
df = pd.DataFrame({"team": ["a", "a", "a", "b"], "salary": [100, 400, 200, 50]}),group_medians(df, "team", "salary")→{"a": 200.0, "b": 50.0}- the same teams,
"salary": [100, np.nan, 120, 80]→{"a": 110.0, "b": 80.0} "team": ["a", "a", "b", "b"],"salary": [100, 120, np.nan, np.nan]→{"a": 110.0}
Constraints: the column by has no missing values, and column holds numbers and missing values; with an even number of values the median is the mean of the two central ones; missing values are skipped, and a group without a single value is left out of the dictionary.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.