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

如何用Pandas按条件为DataFrame新增Value-2列?

解决DataFrame新增列问题

可以用以下两种常用方法实现需求:

方法一:嵌套numpy.where判断

通过两层条件判断直接赋值,逻辑清晰:

import pandas as pd
import numpy as np

# 假设你的DataFrame变量名为df
df['Value-2'] = np.where(df['Value-1'] < 500, 0.5,
                         np.where(df['Value-1'] < 1000, 1, np.nan))

注:如果存在Value-1 >= 1000的行,可将最后一个np.nan替换为你需要的默认值。

方法二:pandas.cut区间分箱

适合按连续区间划分的场景,代码更简洁:

import pandas as pd
import numpy as np

df['Value-2'] = pd.cut(df['Value-1'],
                       bins=[-np.inf, 500, 1000, np.inf],
                       labels=[0.5, 1, np.nan])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:00:59