I'm struggling with setting a cell value to a tuple or list with pandas using .replace()
Here is my dictionary:
to_replace = {0: (0.6509803921568628, 0.807843137254902, 0.8901960784313725, 1.0),
1: (0.12156862745098039, 0.47058823529411764, 0.7058823529411765, 1.0),
2: (0.6980392156862745, 0.8745098039215686, 0.5411764705882353, 1.0)}
Here is my dataframe
df = pd.DataFrame({'ArrayID': {3: 'C112216_S47', 2: 'H9_S73', 1: 'NI_ADULT_S72', 0: 'org_H14_Colon_p13_S1'},
'Category': {3: 'C112216_S47', 2: 'H9_S73', 1: 'NI_ADULT_S72', 0: 'org_H14_Colon_p13_S1'},
'cval': {3: 2, 2: 0, 1: 1, 0: 0}})
And here is my attempt to add a new column "color" with each tuple above:
df["color"] = df["cval"].replace(to_replace)
The output I'd like is
ArrayID Category cval color
3 C112216_S47 C112216_S47 2 (0.6980392156862745, 0.8745098039215686, 0.5411764705882353, 1.0)
2 H9_S73 H9_S73 0 (0.6509803921568628, 0.807843137254902, 0.8901960784313725, 1.0)
1 NI_ADULT_S72 NI_ADULT_S72 1 (0.12156862745098039, 0.47058823529411764, 0.7058823529411765, 1.0)
0 org_H14_Colon_p13_S1 org_H14_Colon_p13_S1 0 (0.6509803921568628, 0.807843137254902, 0.8901960784313725, 1.0)
CodePudding user response:
Use map
instead of replace
:
df["color"] = df["cval"].map(to_replace)
Output:
ArrayID Category cval color
3 C112216_S47 C112216_S47 2 (0.6980392156862745, 0.8745098039215686, 0.5411764705882353, 1.0)
2 H9_S73 H9_S73 0 (0.6509803921568628, 0.807843137254902, 0.8901960784313725, 1.0)
1 NI_ADULT_S72 NI_ADULT_S72 1 (0.12156862745098039, 0.47058823529411764, 0.7058823529411765, 1.0)
0 org_H14_Colon_p13_S1 org_H14_Colon_p13_S1 0 (0.6509803921568628, 0.807843137254902, 0.8901960784313725, 1.0)