I am trying to map or replace values in a Pandas data frame based on value pairs in a dictionary. The value pairs are in a list, and I want to split the items into their own columns. There are always only two items in the value pair list.
Stand-alone example
mydf = pd.DataFrame({"x": [1, 2, 3, 4], "cat": ["text1", "text3", "text1", "text4"]})
mydict = {
"text1": ["a15", "b3"],
"text2": ["a6", "b1"],
"text3": ["a3", "b3"],
"text4": ["a1", "b12"],
}
display(mydf)
Desired result
Efforts
Based on a similar question here I tried the following:
new_map = {str(x): str(k) for k, v in mydict.items() for x in v}
mydf['left'] = mydf['cat']
mydf['left'].map(new_map)
Which doesn't work, it returns this:
I also tried the following (based on this):
new_map = {str(x): str(k) for k, v in mydict.items() for x in v}
mydf['left'] = mydf.index.map(lambda x: new_map[x])
Which resulted in the error KeyError: 0