Skip to main content
 首页 » 编程设计

python之使用 Pandas 根据另一列的值选择一列

2025年05月04日19artech

Pandas 数据框的结构如下:

              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 列:

              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。

请您参考如下方法:

使用DataFrame.lookup将 price_ 添加到列 color 以按列名称匹配:

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