python - How to replace dataframe column values with dictionary keys? -


suppose have dictionary:

dict = {"1" : "a", "2" : "b" , "3" : "c"} 

and data frame

df = pd.dataframe() df["id"] = pd.series(["a","b","c"]) df["desc"] = pd.series(["fruits","vegs","meat"]) 

the dataframe this:

enter image description here

how replace values in column df["id"] dictionary keys have 1,2,3 in df["id"] instead of a,b,c?

first create reverse mapping:

in [363]: dict2 = {v : k k, v in dict_.items()} 

the assumption made here values unique. 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 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, recommend use different name dict, because there's builtin name.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -