I had the following data-cleaning question in an interview test that I struggled on (I've changed the details to anonymise it and protect the company's interview process)
Given the following dataframe
df
, return a new series withday
as the index, and a single column with the set of meals consumed by everyone who ate that day (i.e, both Alice and Bob on days 1 and 3, but only Alice on day 2). Do not use for loops or list comprehensions, only method chaining and a single lambda function that accepts only a single argument.
df = pd.DataFrame({'day':[1, 2, 3, 1, 3]*3,
'person':['Alice', 'Alice', 'Alice', 'Bob', 'Bob']*3,
'meal':['breakfast', 'breakfast', 'breakfast', 'breakfast', 'breakfast']+
['lunch', 'brunch', 'brunch', 'lunch', 'lunch']+
['dessert', 'dinner', 'snack', 'beer', 'dessert']
})
In other words, the goal is to obtain the following dataframe:
goal = pd.DataFrame({'day':[1, 2, 3],
'meal':[{'breakfast', 'lunch'},
{'breakfast', 'brunch', 'dinner'},
{'breakfast'}]
}).set_index('day')
Does anyone know how to do this? Thanks!
df.groupby('day').apply(lambda x: set(x['meal']))
$\endgroup$