Python 根据另一列的值选择一列

Python 根据另一列的值选择一列,python,pandas,numpy,Python,Pandas,Numpy,具有如下结构的熊猫数据帧: color price_blue price_red price_green date 2019-01-01 green 10 20 30 2019-01-02 red 40 50 60 2019-01-03 blue 11 12

具有如下结构的熊猫数据帧:

              color    price_blue   price_red   price_green
date
2019-01-01    green            10          20            30
2019-01-02      red            40          50            60
2019-01-03     blue            11          12            13
如何根据每行颜色列的值添加价格列:

              color    price_blue   price_red   price_green    price
date
2019-01-01    green            10          20            30       30
2019-01-02      red            40          50            60       50
2019-01-03     blue            11          12            13       11
虽然一个类似于apply的解决方案似乎很容易,但在这种情况下,由于数据集相对较大,需要一个向量化的解决方案

此外,像np.where这样的解决方案只需很少的颜色选择就可以正常工作,但是在实际情况中,有20多种不同的颜色,因此如果有很多嵌套的where,那么这将非常不切实际。

与“向列颜色添加价格”一起使用,以便按列名称匹配:

df['price'] = df.lookup(df.index, 'price_' + df['color'])
print (df)
            color  price_blue  price_red  price_green  price
2019-01-01  green          10         20           30     30
2019-01-02    red          40         50           60     50
2019-01-03   blue          11         12           13     11
与“将价格添加到列颜色”一起使用,以便按列名称进行匹配:

df['price'] = df.lookup(df.index, 'price_' + df['color'])
print (df)
            color  price_blue  price_red  price_green  price
2019-01-01  green          10         20           30     30
2019-01-02    red          40         50           60     50
2019-01-03   blue          11         12           13     11