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:
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
Post a Comment