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

如何创建新列并按uid为其分配0或1值

为DataFrame新增条件列(按指定uid分配0/1)

方法1:利用isin()生成布尔列并转换为数值

先定义需要标记为1的uid列表,通过isin()判断每行uid是否在目标列表中,再将布尔值转为整数(True→1,False→0):

import pandas as pd

# 原始DataFrame
df = pd.DataFrame({'uid': [1, 2, 3, ...]})

# 指定需要标记为1的uid集合
target_uids = [3]  # 替换成你的目标uid

# 新增new列
df['new'] = df['uid'].isin(target_uids).astype(int)

方法2:使用np.where()实现条件赋值

通过numpy的where()函数直接根据条件赋值,逻辑更直观:

import pandas as pd
import numpy as np

# 原始DataFrame
df = pd.DataFrame({'uid': [1, 2, 3, ...]})

target_uids = [3]

# 新增new列:满足条件赋值1,否则赋值0
df['new'] = np.where(df['uid'].isin(target_uids), 1, 0)

示例输出

执行代码后,DataFrame会呈现如下形式:

uid  new
0    1    0
1    2    0
2    3    1
..  ..  ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:45:26