Danish
Danish

Reputation: 2871

Sort a dictionary in a column in pandas

I have a dataframe as shown below.

user_id     Recommended_modules                     Remaining_modules
1           {A:[5,11], B:[4]}                       {A:2, B:1}
2           {A:[8,4,2], B:[5], C:[6,8]}             {A:7, B:1, C:2}
3           {A:[2,3,9], B:[8]}                      {A:5, B:1}
4           {A:[8,4,2], B:[5,1,2], C:[6]}           {A:3, B:4, C:1} 

Brief about the dataframe:

In the column Recommended_modules A, B and C are courses and the numbers inside the list are modules.

Key(Remaining_modules) = Course name

value(Remaining_modules) = Number of modules remaining in that course

From the above I would like to reorder the recommended_modules column based on the values in the Remaining_modules as shown below.

Expected Output:

user_id     Ordered_Recommended_modules             Ordered_Remaining_modules
1           {B:[4], A:[5,11]}                       {B:1, A:2}
2           {B:[5], C:[6,8], A:[8,4,2]}             {B:1, C:2, A:7}
3           {B:[8], A:[2,3,9]}                      {B:1, A:5}
4           {C:[6], A:[8,4,2], B:[5,1,2]}           {C:1, A:3, B:4} 

Explanation:

For user_id = 2, Remaining_modules = {A:7, B:1, C:2}, sort like this {B:1, C:2, A:7}

similarly arrange Recommended_modules also in the same order as shown below {B:[5], C:[6,8], A:[8,4,2]}.

Upvotes: 1

Views: 123

Answers (1)

jezrael
jezrael

Reputation: 862511

It is possible, only need python 3.6+:

def f(x):
    #https://stackoverflow.com/a/613218/2901002
    d1 = {k: v for k, v in sorted(x['Remaining_modules'].items(), key=lambda item: item[1])}
    L = d1.keys()
    #https://stackoverflow.com/a/21773891/2901002
    d2 = {key:x['Recommended_modules'][key] for key in L if key in x['Recommended_modules']}
    x['Remaining_modules'] = d1
    x['Recommended_modules'] = d2
    return x

df = df.apply(f, axis=1)
print (df)
   user_id                         Recommended_modules  \
0        1                    {'B': [4], 'A': [5, 11]}   
1        2     {'B': [5], 'C': [6, 8], 'A': [8, 4, 2]}   
2        3                  {'B': [8], 'A': [2, 3, 9]}   
3        4  {'C': [6], 'A': [8, 4, 2], 'B': [5, 1, 2]}   

          Remaining_modules  
0          {'B': 1, 'A': 2}  
1  {'B': 1, 'C': 2, 'A': 7}  
2          {'B': 1, 'A': 5}  
3  {'C': 1, 'A': 3, 'B': 4}  

Upvotes: 3

Related Questions