[英]Pandas: search multiple columns and return column with found value
I'm try to do some auditing for our purchase orders, and I created this dataframe (here's a csv sample of it): 我尝试对我们的采购订单进行一些审核,并创建了此数据框(此处是一个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
In my data source, some products get different breaks, depending on the quantity purchased. 在我的数据源中,某些产品会根据购买的数量而有所不同。 Hence the columns
BuyQty1
and BuyQty1Cost
. 因此,列
BuyQty1
和BuyQty1Cost
。 Qty
and LineCost
are the values I need to audit. Qty
和LineCost
是我需要审核的值。 So, what I'm trying to do is: 所以,我想做的是:
Check what quantity break corresponds to the value on the column Qty
. 检查哪个数量中断对应于“
Qty
”列上的值。 Example a Qty
of 48 implies that the break is BuyQty2
, and the corresponding price should be BuyQty2Cost
. 例如,
Qty
为48表示中断为BuyQty2
,对应价格应为BuyQty2Cost
。
Then add a column with the ratio of LineCost/BuyQty2Cost
. 然后以
LineCost/BuyQty2Cost
的比率添加一列。 It would be BuyQty3Cost
in the case of SIGN2BK
(2nd line). 这将是
BuyQty3Cost
在的情况下SIGN2BK
(2号线)。
How should I tackle this? 我该如何解决?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.