gpt4 book ai didi

python - 根据另一个表中的多个列在一个表中创建一列 [python]

转载 作者:太空宇宙 更新时间:2023-11-04 11:13:36 25 4
gpt4 key购买 nike

我正在创建一个 csv 表,其中包含有关我所有订单的信息。现在我想卖掉这些元素,但我想根据元素的价格添加额外的附加费。我创建了一个带有 surcharge 的新表,其中有名为“from”和“to”的列,我必须从中比较商品价格,然后在销售价格中包含正确的附加费。

但是我做不到。我尝试了不同的方法,但似乎都不起作用。任何帮助都会很好:)

我的表格是这样的:

    OrderNo      NetPerPiece costsDividedPerOrder  HandlingPerPiece

0 7027514279 44.24 0.008007 0.354232

1 7027514279 15.93 0.008007 0.127552

2 7027514279 15.93 0.008007 0.127552

3 7027514279 15.93 0.008007 0.127552

4 7027514279 15.93 0.008007 0.127552
surcharges = {'surcharge': [0.35, 0.25, 0.2, 0.15, 0.12, 0.1],
'from': [0, 20, 200, 500, 1500, 5000],
'to' : [20, 200, 500, 1500, 5000,1000000000] }
surchargeTable = DataFrame(surcharges, columns=['surcharge', 'from', 'to'])


productsPerOrder['NetPerpieceSale'] = numpy.where(((productsPerOrder['NetPerPiece'] >= surchargeTable['from']) & (productsPerOrder['NetPerPiece'] < surchargeTable['to'])), surchargeTable['surcharge'])


#I also tried this:

for index, row in productsPerOrder.iterrows():
if row['NetPerPiece'] >= surchargeTable['from'] & row['NetPerPiece'] < surchargeTable['to']:
productsPerOrder.loc[index,'NerPerPieceSale'] = surchargeTable.loc[row,'NetPerPieceSale'].values(0)

我希望它看起来像这样:

 OrderNo   NetPerPiece costsDividedPerOrder  HandlingPerPiece NetPerPieceSale

0 7027514279 44.24 0.008007 0.354232 0.25

1 7027514279 15.93 0.008007 0.127552 0.35

2 7027514279 15.93 0.008007 0.127552 0.35

3 7027514279 15.93 0.008007 0.127552 0.35

4 7027514279 15.93 0.008007 0.127552 0.35

提醒一下,带有项目的文件要大得多,我只显示了 csv 列表的头部。所以表格的长度不同

SurchargeTable 看起来像这样:

 surcharge  from          to
0 0.35 0 20
1 0.25 20 200
2 0.20 200 500
3 0.15 500 1500
4 0.12 1500 5000
5 0.10 5000 1000000000

最佳答案

另一种方法是使用 pd.IntervalIndexmap:

# Create IntervalIndex on surchageTable dataframe
surchargeTable = surchargeTable.set_index(pd.IntervalIndex.from_arrays(surchargeTable['from'],
surchargeTable['to']))

#Use map to pd.Series created from surchargeTable IntervalIndex and surcharge column.
productsPerOrder['NetPerPieceSale'] = productsPerOrder['NetPerPiece'].map(surchargeTable['surcharge'])

productsPerOrder

输出:

      OrderNo  NetPerPiece  costsDividedPerOrder  HandlingPerPiece  NetPerPieceSale
0 7027514279 44.24 0.008007 0.354232 0.25
1 7027514279 15.93 0.008007 0.127552 0.35
2 7027514279 15.93 0.008007 0.127552 0.35
3 7027514279 15.93 0.008007 0.127552 0.35
4 7027514279 15.93 0.008007 0.127552 0.35

关于python - 根据另一个表中的多个列在一个表中创建一列 [python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57576235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com