用DECT重新映射熊猫列中的值我有一本像这样的字典:di = {1: "A", 2: "B"}我想将它应用于Datarame的“col1”列,类似于: col1 col20 w a1 1 22 2 NaN得到: col1 col20 w a1 A 22 B NaN我怎么才能做得最好?出于某种原因,谷歌与此相关的术语只向我展示了如何从dicts生成列的链接,反之亦然:-/
3 回答
元芳怎么了
TA贡献1798条经验 获得超7个赞
钥匙在里面 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']
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
添加回答
举报
0/150
提交
取消