简体   繁体   English

给定熊猫数据框列,如果 X 是字典中的键,如何用字典中的值替换嵌套列表中的元素 X?

[英]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:假设我有一些数据帧 df_smth 使得:

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您可以将Perm_Col列分解为单个列表的列,使用apply执行逐行替换,然后groupby再次重新聚合到列表

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据字典键和值替换熊猫数据框列值? - How to replace pandas dataframe column values based on dictionary key and values? 如何使用 pandas dataframe 系列列元素搜索字典值列表 - how to search list of dictionary values with pandas dataframe series column elements 使用字典替换 Pandas 数据帧上给定索引号的列值 - Using a dictionary to replace column values on given index numbers on a pandas dataframe 使用嵌套字典替换熊猫数据框中的值 - Replace values in pandas dataframe utilizing a nested dictionary 用字典替换 pandas 中给定列的值 - Replace the values of a given column in pandas with a dictionary pandas - 将嵌套字典值映射到dataframe列 - pandas - map nested dictionary values to dataframe column 如何用字典中的查找值替换 pandas DataFrame 列? - How to replace a pandas DataFrame column with lookup values from a dictionary? 如何用另一个列表或字典匹配替换 pandas dataframe 列名 - How to replace pandas dataframe column names with another list or dictionary matching 如何将嵌套字典列表转换为 Pandas dataframe。 但是每个键的嵌套字典列表长度都不相同 - How to convert list of nested dictionary into Pandas dataframe. But nested dictionary list length is not same for every key 如果键匹配,如何用字典的值替换嵌套列表的元素? - How to replace an element of a nested list by the values of a dictionary, if the key matches?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM