元芳怎么了
你的问题有点含糊不清。至少有三两种解释:钥匙在里面di参考索引值钥匙在里面di请参阅df['col1']价值钥匙在里面di参考索引位置(不是OP的问题,而是为了好玩)。下面是每个案例的解决方案。案例1:如果.的钥匙di用于引用索引值,则可以使用update方法:df['col1'].update(pd.Series(di))例如,import pandas as pdimport 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 NaNdi = {0: "A", 2: "B"}# Th
e value at the 0-index is mapped to 'A', the value at the 2-index is mapped to 'B'df['col1'].update(p
d.Series(di))print(df)产量 col1 col21 w a2 B 300 A NaN我已经修改了你最初的文章中的值,所以更清楚的是update正在做。注意键在di与索引值关联。索引值的顺序-即索引地点-不重要。案例2:如果钥匙在di请参阅df['col1']值,然后@DanAllan和@DSM展示了如何用replace:import pandas as pdimport 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
NaNdi = {10: "A", 20: "B"}# The values 10 and 20 are replaced by 'A' and 'B'df['col1'].
replace(di, inplace=True)print(df)产量 col1 col21 w a2 A 300 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 col21 A a2 10 300 B NaN在这里,更改了第一行和第三行,因为di是0和2,它使用Python的基于0的索引引用第一个和第三个位置。