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

如何用Python pandas为CSV数据新增列并通过if else判断填充标识

最优实现方案

pandas处理这类条件列新增的最优实践是用向量化操作,避免逐行迭代,性能远高于你当前用的iterrows循环方案,具体实现如下:

方案1:用np.where实现(推荐,性能最高)

直接用numpy的向量化if else逻辑完成赋值,代码最简洁:

import pandas as pd
import numpy as np

# 读取数据
produtos = pd.read_csv('User.csv', nrows=9)

# 所有Age>=18的行Adul列都填+,否则留空
produtos['Adul'] = np.where(produtos['Age'] >= 18, '+', '')

# 如果你只需要满足「名字是George且成年」的行才填+,就换成下面这行
# produtos['Adul'] = np.where((produtos['Name'] == 'George') & (produtos['Age'] >= 18), '+', '')

print(produtos)

方案2:用apply+显式if else实现

如果你需要写更复杂的多分支if else逻辑,可以用apply方法封装自定义判断函数:

import pandas as pd

produtos = pd.read_csv('User.csv', nrows=9)

def judge_adul(row):
    # 可自定义任意if else逻辑
    if row['Age'] >= 18:
        return '+'
    else:
        return ''
    # 仅George成年才返回+的版本:
    # if row['Name'] == 'George' and row['Age'] >= 18:
    #     return '+'
    # return ''

produtos['Adul'] = produtos.apply(judge_adul, axis=1)
print(produtos)

注意

你当前用的iterrows逐行遍历的方式性能极低,仅适合极小数据量场景,生产环境不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:02