I have the following dataframe. I want to group by a
first. Within each group, I need to do a value count based on c
and only pick the one with most counts if the value in c
is not EMP
. If the value in c
is EMP
, then I want to pick the one with the second most counts. If there is no other value than EMP
, then it should be EMP
as in the case where a = 4.
a c
1 EMP
1 y
1 y
1 z
2 z
2 z
2 EMP
2 z
2 a
2 a
3 EMP
3 EMP
3 k
4 EMP
4 EMP
4 EMP
The expected result would be
a c
1 y
2 z
3 k
4 EMP
This is what I have tried so far: I have managed to sort it in the order I need so I could take the first row. However, I cannot figure out how to implement the condition for EMP
using a lambda function with the drop_duplicates
function as there is only the keep=first
or keep=last
option.
df = df.iloc[df.groupby(['a', 'c']).c.transform('size').mul(-1).argsort(kind='mergesort')]
Edit:
The mode
solution worked, I have an additional question. My dataframe contains about 50 more columns, and I would like to have all of these columns in the end result as well, with the values corresponding to the rows picked using the mode operation and the first value that occurred for the EMP rows. How would I do that? Is there an easier solution than what is mentioned here where you create a dict of functions and pass it to agg
? Using SQL for this is also fine.