[英]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.