[英]How to replace dataframe column values with dictionary keys?
Suppose I have a dictionary: 假设我有一本字典:
dict = {"1" : "A", "2" : "B" , "3" : "C"}
and a data frame 和一个数据框架
df = pd.DataFrame()
df["ID"] = pd.Series(["A","B","C"])
df["Desc"] = pd.Series(["Fruits","Vegs","Meat"])
The dataframe will look like this: 数据框将如下所示:
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
? 如何用字典键替换列
df["ID"]
值,以便我在df["ID"]
有1,2,3
而不是A,B,C
?
First create a reverse mapping: 首先创建一个反向映射:
In [363]: dict2 = {v : k for k, v in dict_.items()}
The assumption made here is that your values are unique. 这里假设您的价值观是独一无二的。 Now you can use
pd.Series.replace
: 现在您可以使用
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
Alternative solution with pd.Series.map
: 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
Also, I recommend you use a different name than dict
, because there's already a builtin with that name. 另外,我建议你使用与
dict
不同的名称,因为已经有一个带有该名称的内置。
Or you can just base on pandas . 或者你可以只基于熊猫。
df.ID=df.ID.map((pd.DataFrame(data=d,index=['Value',]).T.reset_index().set_index('Value'))['index'])
Out[23]:
ID Desc
0 1 Fruits
1 2 Vegs
2 3 Meat
Another way to do this would be: 另一种方法是:
dict1 = pd.DataFrame(dict.items())
dict1.columns = ['ID_1',"ID"]
merge = pd.merge(df,dict1)
del merge['ID']
merge = merge.rename(columns={'ID_1': 'ID'})
Desc ID
0 Fruits 1
1 Vegs 2
2 Meat 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.