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

如何基于pandas DataFrame条件判断规则新增字符串类型标识列

问题描述

我通过如下代码构造了pandas DataFrame:

import pandas as pd
data = {"marks":[1,2,3,4,5,6,7,8,9,10,11,12], "month":['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']}
df2 = pd.DataFrame(data)

预期输出效果
我的需求是根据month列取值新增名为q的字符串列:当month为jan、feb、mar时q取值为'1Q',其余取值为'other'。我尝试编写了如下代码,但运行后无法得到预期结果,请问该如何正确实现?

for i in df2['month']:
   if (i=='jan' or i=='feb' or i=='mar'):
        df2['q'] = '1Q'
   else:
        df2['q']='other'
错误原因

你写的逐行循环中,每次对df2['q']直接赋值是对整个列赋值,而非仅对当前行赋值。循环会遍历所有month值,运行到最后一个值dec时触发else逻辑,最终整个q列都会被覆盖为other,因此得不到预期结果。
pandas处理这类列操作更推荐使用矢量化运算,效率远高于逐行循环,以下是两种常用的正确实现方式:

实现方法

方法1:使用numpy.where(最简洁)

import numpy as np
df2['q'] = np.where(df2['month'].isin(['jan', 'feb', 'mar']), '1Q', 'other')

方法2:使用loc赋值(无需额外导入numpy)

# 先给q列设置默认值为other
df2['q'] = 'other'
# 筛选符合条件的行,将q列赋值为1Q
df2.loc[df2['month'].isin(['jan', 'feb', 'mar']), 'q'] = '1Q'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:24:05