Dataframe populated by lists, how to reorder all the lists by reordering numerically all the lists in a specific column

Viewed 38

I have a dataframe generated by the below dictionary:

input_data= {'Names':[['Ed','Mark','Jim'],['Jiulia','Jhon'],['Phil']],
       'IDs' :[[5,2,3],[7,1],[10]],
       'Address':[['road x','road y','road v'],['road a','road b'],['road z']]}

| Names               | IDs           | Address                      |
| ------------------- | ------------- | ---------------------------- |
| ['Ed','Mark','Jim'] | ['5','2','3'] | ['road x','road y','road v'] |
| ['Jiulia','Jhon']   | ['7','1']     | ['road a','road b']          |
| ['Phil']            | ['10']        | ['road z']                   |

I need to find out how to reorder the ID elements inside the lists in the ID column of the dataframe and then reorder Names and Address accordingly to the IDs new order as shown by the table below which would be the output I need:

| Names               | IDs           | Address                      |
| ------------------- | ------------- | ---------------------------- |
| ['Mark','Jim','Ed'] | ['2','3','5'] | ['road y','road v','road x'] |
| ['Jhon','Jiulia']   | ['1','7']     | ['road b','road a']          |
| ['Phil']            | ['10']        | ['road z']                   |
1 Answers

here is one way do it explode, sort and group it back

df.explode(['Names','IDs','Address']).sort_values('IDs').groupby(level=0).agg(list)

As per your edited question, if quantities are string, this is one way about it, where you convert the IDs to int before sorting. result is same

df2=df.explode(['Names','IDs','Address'])
df2['IDs'] = df2['IDs'].astype('int')
df2.sort_values('IDs').groupby(level=0).agg(list)
    Names           IDs         Address
0   [Mark, Jim, Ed] [2, 3, 5]   [road y, road v, road x]
1   [Jhon, Jiulia]  [1, 7]      [road b, road a]
2   [Phil]          [10]        [road z]

Related