python - 基于另一个表中的多个列在一个表中创建一个列[python]
问题描述
我正在创建一个 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.IntervalIndex
and map
:
# 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
推荐阅读
- php - 多张图片验证不起作用 - Laravel 8
- javascript - 寻找走出迷宫的方法
- android - 导出 Room 数据库并附加到电子邮件 Android Kotlin
- amazon-s3 - 将数据从关系数据库传输到 S3 时是否保留了关系?
- oracle-sqldeveloper - 为什么我无法使用 Oracle XE 并出现错误:“IO 错误:网络适配器无法建立连接供应商代码 17002”?
- javascript - 嵌入对象到数组
- r - 顶点标签从 id 更改为 igraph 中的另一列
- watchkit - Apple Watch 陀螺仪和方向更新率?
- jestjs - 本地测试运行良好时,可能导致 CI 测试失败的原因是什么?
- hive - Hive 未在 ubuntu java.lang.ClassCastException 上运行