I have a DataFrame named df, and I want to count the top frequency elements in column app_0, app_1 and app_2 on different sex.
import pandas as pd
import numpy as np
df=pd.DataFrame({'id':[1,2,3,4],'app_0':['a','b','c','d'],
'app_1':['b','c','d',np.nan],'app_2':['c','b','a','a'],'sex':[0,0,1,1]})
Input:
df
id app_0 app_1 app_2 sex
0 1 a b c 0
1 2 b c b 0
2 3 c d a 1
3 4 d NaN a 1
As you see, the sex of both id 1 and id 2 is 0. For sex 0, b appears the most in column app_0, app_1 and app_2, c appears the second most. So for id 1 and id 2, the most frequency element is b, and the second most is c.
Expected:
df
id app_0 app_1 app_2 sex top_1 top_2
0 1 a b c 0 b c
1 2 b c b 0 b c
2 3 c d a 1 a d
3 4 d NaN a 1 a d