如何用字典键替换数据框列值? [英] How to replace dataframe column values with dictionary keys?
本文介绍了如何用字典键替换数据框列值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一本字典:
dict = {"1" : "A", "2" : "B" , "3" : "C"}
和一个数据框
df = pd.DataFrame()
df["ID"] = pd.Series(["A","B","C"])
df["Desc"] = pd.Series(["Fruits","Vegs","Meat"])
数据框将如下所示:
如何用字典键替换列df["ID"]
中的值,以便在df["ID"]
中使用1,2,3
而不是A,B,C
?
How would I replace values in column df["ID"]
with dictionary keys so that I have 1,2,3
in df["ID"]
instead of A,B,C
?
推荐答案
首先创建一个反向映射:
First create a reverse mapping:
In [363]: dict2 = {v : k for k, v in dict_.items()}
这里所做的假设是您的价值观是唯一的.现在您可以使用pd.Series.replace
:
The assumption made here is that your values are unique. Now you can use pd.Series.replace
:
In [367]: df.ID = df.ID.replace(dict2); df
Out[367]:
ID Desc
0 1 Fruits
1 2 Vegs
2 3 Meat
使用pd.Series.map
的替代解决方案:
Alternative solution with pd.Series.map
:
In [380]: df.ID = df.ID.map(dict2); df
Out[380]:
ID Desc
0 1 Fruits
1 2 Vegs
2 3 Meat
此外,我建议您使用不同于dict
的名称,因为已经有一个内置名称.
Also, I recommend you use a different name than dict
, because there's already a builtin with that name.
这篇关于如何用字典键替换数据框列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文