Python Pandas 添加 Tuple/List 到单元格

Python Pandas Add Tuple/List to Cell

我正在努力使用 .replace()

将单元格值设置为 pandas 的元组或列表

这是我的词典:

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)}

这是我的数据框

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}})

这是我尝试为上面的每个元组添加一个新列“颜色”:

df["color"] = df["cval"].replace(to_replace)

我想要的输出是

                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)

使用map代替replace

df["color"] = df["cval"].map(to_replace)

输出:

                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)