Pandas:搜索多个列并返回具有找到值的列

时间:2015-06-29 17:56:49

标签: python pandas

我正在尝试对我们的采购订单进行一些审核,我创建了这个数据框(这是一个csv示例):

ProductName,Qty,LineCost,BuyQty1,BuyQty1Cost,BuyQty2,BuyQty2Cost,BuyQty3,BuyQty3Cost

SIGN2WH,48,40.63,5,43.64,48,40.63,72,39.11
SIGN2BK,144,39.11,5,43.64,48,40.63,72,39.11

在我的数据源中,根据购买的数量,某些产品会有不同的休息时间。因此列BuyQty1BuyQty1CostQtyLineCost是我需要审核的值。所以,我要做的是:

  1. 检查哪个数量中断对应于列上的值 Qty。示例Qty为48表示中断为BuyQty2, 相应的价格应为BuyQty2Cost

  2. 然后添加比率为LineCost/BuyQty2Cost的列。 BuyQty3Cost(第二行)的情况为SIGN2BK

  3. 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

import pandas as pd

def calculate_break_level(row):
    if row.Qty >= row.BuyQty3:
        return row.BuyQty3Cost
    elif row.Qty >= row.BuyQty2:
        return row.BuyQty2Cost
    else:
        return row.BuyQty1Cost

# apply the function row-by-row by specifying axis=1
# the newly produced Line_Cost is in the last column.
df['Line_Cost'] = df.apply(calculate_break_level, axis=1)

Out[58]: 
  ProductName  Qty  LineCost  BuyQty1  BuyQty1Cost  BuyQty2  BuyQty2Cost  BuyQty3  BuyQty3Cost  Line_Cost
0     SIGN2WH   48     40.63        5        43.64       48        40.63       72        39.11      40.63
1     SIGN2BK  144     39.11        5        43.64       48        40.63       72        39.11      39.11