简体   繁体   中英

Given the pandas dataframe column, how to replace elements X in a nested list with the values in dictionary if X is a key in a dictionary?

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!

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM