python- 如何使用另一列中的值作为 Pandas 中已定义字典的键来更新列?

python- How to update a column using value in another column as key to a defined dictionary in Pandas?

我有一本这样的字典:di = {1: "A", 2: "B"}

我想将它应用于数据框的 "col3" 列,类似于使用 "col1" 中的值作为 di 的键:

     col1   col2   col3
0       w      a     U
1       1      2     V
2       2    NaN     W

获得:

     col1   col2   col3
0       w      a     U
1       1      2     A
2       2    NaN     B

我怎样才能最好地做到这一点?我找到的所有答案都是 replace columns considering them as keys.

您可以在 col1 上进行映射,并用 col3 中的值填充缺失值:

df.col3 = df.col1.map(di).fillna(df.col3)