你的问题有点模棱两可。至少有
三
两种解释:
-
钥匙在
di
参考索引值
-
钥匙在
迪
参照
df['col1']
价值观
-
钥匙在
迪
参考索引位置(不是OP的问题,而是为了好玩而抛出的。)
以下是每种情况的解决方案。
案例1:
如果
迪
是指索引值,然后可以使用
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
我修改了你原帖中的值,这样就更清楚了
更新
正在做。
注意钥匙是如何进入的
迪
与索引值关联。索引值的顺序——即,索引
位置
--没关系。
案例2:
如果钥匙在
迪
参照
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
注意,在这种情况下,如何在
迪
已更改为匹配
价值观
在里面
DF[COL1′]
.
案例3:
如果钥匙在
迪
参考索引位置,然后可以使用
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
在这里,第一行和第三行被修改了,因为
迪
是
0
和
2
,它使用python基于0的索引引用第一个和第三个位置。