You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于elif逻辑为DataFrame多列分配数值的技术实现问题

解决DataFrame多列按逻辑分配物料数量的问题

现有代码逻辑

已实现type为Linear Section时,qty在指定区间的物料分配:

import pandas as pd
import numpy as np

# 示例DataFrame
df = pd.DataFrame({
    'type': ['Linear Section']*5,
    'qty': [7, 8.5, 9.5, 10.5, 46],
    'wall sides': [1]*5
})

# 基础区间分配
df['8footer'] = ((df[(df['type'] == 'Linear Section') & (df.qty <= 8.17)]['qty'] * df['wall sides'])).fillna(0)
df['9footer'] = ((df[(df['type'] == 'Linear Section') & (df.qty > 8.17) & (df.qty <= 9.17)]['qty'] * df['wall sides'])).fillna(0)
df['10footer'] = ((df[(df['type'] == 'Linear Section') & (df.qty > 9.17) & (df.qty <= 10.17)]['qty'] * df['wall sides'])).fillna(0)
df['12footer'] = ((df[(df['type'] == 'Linear Section') & (df.qty > 10.17) & (df.qty <= 14)]['qty'] * df['wall sides'])).fillna(0)

待处理场景:qty > 14

需要将qty按最大规格12拆分:

  • 整除12的部分直接计入12footer
  • 余数x = qty % 12按区间分配到对应列:
    • x < 8.17 → 8footer
    • 8.17 < x ≤ 9.17 → 9footer
    • 9.17 < x ≤ 10.17 → 10footer
    • x > 10.17 → 12footer

解决方案(向量化实现)

通过向量化运算高效处理,避免循环:

# 筛选目标行
mask = (df['type'] == 'Linear Section') & (df['qty'] > 14)
target_qty = df.loc[mask, 'qty'] * df.loc[mask, 'wall sides']

# 计算整除部分和余数
div_part = (target_qty // 12) * 12
remainder = target_qty % 12

# 创建余数分配的临时DataFrame
remainder_df = pd.DataFrame(0, index=target_qty.index, columns=['8footer', '9footer', '10footer', '12footer'])

# 按余数区间赋值
remainder_df.loc[remainder < 8.17, '8footer'] = remainder
remainder_df.loc[(remainder > 8.17) & (remainder <= 9.17), '9footer'] = remainder
remainder_df.loc[(remainder > 9.17) & (remainder <= 10.17), '10footer'] = remainder
remainder_df.loc[remainder > 10.17, '12footer'] = remainder

# 加上整除部分到12footer
remainder_df['12footer'] += div_part

# 更新原DataFrame
df.loc[mask, remainder_df.columns] = remainder_df

最终结果

执行后得到符合预期的输出:

indextypeqtywall sides8footer9footer10footer12footer
0Linear Section717000
1Linear Section8.5108.500
2Linear Section9.51009.50
3Linear Section10.5100010.5
4Linear Section461001036

注意事项

  • 自动适配wall sides的倍数计算,与原有逻辑保持一致
  • 向量化运算性能优于apply或循环,适合大数据集
  • 先执行基础区间分配,再覆盖qty>14的场景,确保逻辑不冲突

内容的提问来源于stack exchange,提问作者canconfirm24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:10:28