Home > front end >  Given the pandas dataframe column, how to replace elements X in a nested list with the values in dic
Given the pandas dataframe column, how to replace elements X in a nested list with the values in dic

Time:10-28

Hope you are doing well. Let's say I have some dataframe df_smth such that:

in  [1]: df_smth 
out [1]: 

|          |       Dict_Col |                Perm_Col | 
| -------- |-------------   | ------------------------|
| 0        | {1:a, 2:b, 3:c}| [[1, 2], [1, 3], [2, 3]]|
| 1        | {1:a, 3:c, 2:b}| [[1, 1], [2, 3], [1, 3]]|

And I want to get

|          |            New_Perm_Col | 
| -------- | ------------------------|
| 0        | [[a, b], [a, c], [b, c]]|
| 1        | [[a, a], [b, c], [a, c]]|

Thanks!

CodePudding user response:

You can explode the Perm_Col column into a column of single lists, use apply to perform row-wise replacements, then groupby to reaggregate to lists again

df2 = pd.DataFrame(
    df_smth.explode('Perm_Col')
           .apply(lambda row: [row.Dict_Col.get(x, x) for x in row.Perm_Col], axis=1)
           .groupby(lambda x: x)
           .apply(lambda g: list(g))
           .rename('Perm_Col')
)
df2
# returns:
                   Perm_Col
0  [[a, b], [a, c], [b, c]]
1  [[a, a], [b, c], [a, c]]
  • Related