你的问题有点含糊不清 . 至少有三种解释:
di 中的键指的是索引值
di 中的键指的是 df['col1'] 值
di 中的键是指索引位置(不是OP的问题,而是为了好玩而引入) .
以下是每种情况的解决方案 .
Case 1: 如果 di 的键用于引用索引值,则可以使用 update 方法:
df['col1'].update(pd.Series(di))
例如,
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
# col1 col2
# 1 w a
# 2 10 30
# 0 20 NaN
di = {0: "A", 2: "B"}
# The value at the 0-index is mapped to 'A', the value at the 2-index is mapped to 'B'
df['col1'].update(pd.Series(di))
print(df)
产量
col1 col2
1 w a
2 B 30
0 A NaN
我已经修改了原始帖子中的值,因此更清楚 update 正在做什么 . 请注意 di 中的键如何与索引值相关联