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

如何在Pandas DataFrame中标记列表内的数值

解决方法

假设你有如下示例数据:

import pandas as pd

# 创建示例DataFrame
df = pd.DataFrame({'数值列': [10, 20, 30, 40, 50, 60]})
# 包含目标元素的列表
target_elements = [20, 40, 60]

你可以用Pandas的isin()方法快速判断元素是否在目标列表中,再将布尔结果转为整数(True对应1,False对应0),新增一列存储标记:

# 添加标记列
df['标记'] = df['数值列'].isin(target_elements).astype(int)

执行后得到的DataFrame如下:

数值列  标记
0    10   0
1    20   1
2    30   0
3    40   1
4    50   0
5    60   1

如果你的DataFrame有多列,只需把代码中的'数值列'替换为你要判断的目标列名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:24:11