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

如何在Pandas DataFrame中按列条件计算并添加Revenue列?

解决方法

先排查常见报错原因

  • 确认列名正确性:检查DataFrame x 中是否存在精确匹配的Cost_Buckets和Order_total列,注意大小写、空格、拼写差异(比如是否写成cost_buckets或OrderTotal)。
  • 检查数据类型:确保Order_total是数值类型(int/float),如果是字符串格式,先转换为数值:
    x['Order_total'] = pd.to_numeric(x['Order_total'], errors='coerce')
    
    errors='coerce'会把无法转换的值设为NaN,后续可根据需求处理这些缺失值。

修正后的代码实现

你原代码的逻辑本身没问题,但嵌套np.where可读性较差,推荐用pandas.loc分条件赋值,更直观且易维护:

# 初始化Revenue列为0(对应"1. Less than 5"的情况)
x['Revenue'] = 0
# 条件1:Cost_Buckets为"2. 5 to 19"时,赋值为Order_total的15%
x.loc[x['Cost_Buckets'] == "2. 5 to 19", 'Revenue'] = 0.15 * x['Order_total']
# 条件2:Cost_Buckets为"3. More than 20"时,赋值为Order_total的25%
x.loc[x['Cost_Buckets'] == "3. More than 20", 'Revenue'] = 0.25 * x['Order_total']

如果坚持用np.where,确保列名和数据类型正确即可,原代码逻辑无误:

x['Revenue'] = np.where(
    x['Cost_Buckets'] == "2. 5 to 19",
    0.15 * x['Order_total'],
    np.where(
        x['Cost_Buckets'] == "3. More than 20",
        0.25 * x['Order_total'],
        0
    )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:45:15