你的问题有点含糊。至少有三种两种解释:
-
di 中的键引用索引值
-
di 中的键引用df['col1'] 值
-
di 中的键是指索引位置(不是 OP 的问题,而是为了好玩。)
以下是每种情况的解决方案。
案例 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 中的键是如何与索引值相关联的。索引值的顺序——即索引locations——无关紧要。
案例 2:
如果di 中的键引用df['col1'] 值,那么@DanAllan 和@DSM 将展示如何使用replace 实现这一点:
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
print(df)
# col1 col2
# 1 w a
# 2 10 30
# 0 20 NaN
di = {10: "A", 20: "B"}
# The values 10 and 20 are replaced by 'A' and 'B'
df['col1'].replace(di, inplace=True)
print(df)
产量
col1 col2
1 w a
2 A 30
0 B NaN
注意在这种情况下di 中的键是如何更改为匹配df['col1'] 中的值。
案例 3:
如果di 中的键是指索引位置,那么您可以使用
df['col1'].put(di.keys(), di.values())
因为
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
di = {0: "A", 2: "B"}
# The values at the 0 and 2 index locations are replaced by 'A' and 'B'
df['col1'].put(di.keys(), di.values())
print(df)
产量
col1 col2
1 A a
2 10 30
0 B NaN
在这里,第一行和第三行被改变了,因为di 中的键是0 和2,使用 Python 从 0 开始的索引指的是第一和第三位置。