gpt4 book ai didi

python - 使用多列同时将字典映射到数据框

转载 作者:行者123 更新时间:2023-12-04 00:55:08 24 4
gpt4 key购买 nike

希望在使用字典创建新列值的同时使用多个列来创建新列。下面的简单示例:

df:

Col1     Col2    Col3
Dog Bird Cat
Blue Red Black
Bad Sad Glad

my_dict = {'Bird': 'AAA','Blue':'BBB','Glad':'ZZZ'}

期望的 df:

Col1     Col2    Col3      NewCol
Dog Bird Cat AAA
Blue Red Black BBB
Bad Sad Glad ZZZ

我玩过 map 函数 (df.NewCol = df.Col.map(my_dict))...但它只允许我使用一列来搜索字典中的键。我需要 Col1、Col2 和 Col3 列来搜索我的字典以创建 NewCol。

有什么想法吗?谢谢!

最佳答案

选项 1:应用 mapffill。这不假设每行一个有效条目。

# this will take the last occurrence of valid entry in a row
# change to .bfill(1).iloc[:,0] to get the first
df['NewCol'] = df.apply(lambda x: x.map(my_dict)).ffill(1).iloc[:,-1]

选项 2:映射堆栈并分配。这种方法假定每行只有一个有效条目。

df['NewCol'] = (df.stack().map(my_dict)
.reset_index(level=1, drop=True)
.dropna()
)

输出:

   Col1  Col2   Col3 NewCol
0 Dog Bird Cat AAA
1 Blue Red Black BBB
2 Bad Sad Glad ZZZ

关于python - 使用多列同时将字典映射到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63080823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com