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

如何在Python中按条件重新计算列值:将小于30的kg转为磅

解决DataFrame Weight列单位转换问题

你的代码错误在于np.where函数需要三个必填参数:判断条件、条件成立时的返回值、条件不成立时的返回值,你只传入了前两个,所以会报错。

方法一:修正np.where用法

这是最简洁的向量式处理方法,效率很高:

import numpy as np
import pandas as pd

# 替换成你的DataFrame变量
df['Weight'] = np.where(df['Weight'] < 30, df['Weight'] * 2.2, df['Weight'])

逻辑说明:当Weight值小于30时,乘以2.2转换为磅;大于等于30时,直接保留原数值。

方法二:用apply函数(更直观,适合新手理解)

如果你觉得向量式处理不好理解,可以用逐元素处理的方式:

def convert_weight(weight):
    if weight < 30:
        return weight * 2.2
    return weight

df['Weight'] = df['Weight'].apply(convert_weight)

逻辑说明:定义一个判断函数,通过apply对Weight列的每个值单独处理,符合条件就转换,否则返回原值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:42:07