pandas 如何用字典键替换数据框列值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45787481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:16:58  来源:igfitidea点击:

How to replace dataframe column values with dictionary keys?

pythonpandasdataframereplace

提问by farheen

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:

数据框将如下所示:

enter image description here

在此处输入图片说明

How would I replace values in column df["ID"]with dictionary keys so that I have 1,2,3in df["ID"]instead of A,B,C?

我将如何df["ID"]用字典键替换列中的值,以便我使用1,2,3indf["ID"]而不是A,B,C

回答by cs95

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,因为已经有一个具有该名称的内置函数。

回答by YOBEN_S

Or you can just base on pandas .

或者你可以只基于 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

回答by Gayatri

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