How to replace dataframe column values with dictio

2019-08-14 07:26发布

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,3 in df["ID"] instead of A,B,C?

3条回答
何必那么认真
2楼-- · 2019-08-14 08:04

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
查看更多
别忘想泡老子
3楼-- · 2019-08-14 08:16

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
查看更多
成全新的幸福
4楼-- · 2019-08-14 08:18

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:

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:

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.

查看更多
登录 后发表回答