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

基于正则匹配动态列生成新列的Pandas技术问题

Pandas动态列条件生成新列解决方案

问题描述

现有如下Pandas DataFrame,包含first、col1、col2、col3、row1列:

import pandas as pd
df = pd.DataFrame({'first': ['1', '2', '3', '4', '5', '6', '7', '8'], 
                   'col1': ['yes', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no'], 
                   'col2': ['yes', 'yes', 'no', 'no' ,'yes', 'yes' ,'no', 'no'], 
                   'col3': ['yes', 'no', 'yes', 'no','yes', 'no','yes', 'no'], 
                   'row1':['4','5','7','3','7','3','79','8']})

需要生成新列new_one:当所有匹配col*正则模式的列全为'no'时,new_one为'no',否则为'yes'。且这类col*列的数量是动态的,无法通过硬编码列名实现。

可行解决方案

方法一:使用filter筛选列 + numpy.where判断

通过正则筛选目标列后,逐行判断是否全为'no',再映射结果:

import numpy as np

# 筛选所有以col开头的列
target_cols = df.filter(regex='^col')

# 生成new_one列:全为no则设为no,否则为yes
df['new_one'] = np.where((target_cols == 'no').all(axis=1), 'no', 'yes')
  • df.filter(regex='^col')自动匹配所有以col开头的列,适配动态列数量需求
  • (target_cols == 'no').all(axis=1)返回每行的布尔值:True表示该行所有目标列都是'no'
  • np.where根据布尔值映射对应的字符串结果

方法二:使用any判断非no情况 + 布尔值映射

另一种思路:只要有一个目标列不是'no',就返回'yes',否则返回'no':

target_cols = df.filter(regex='^col')
df['new_one'] = (target_cols != 'no').any(axis=1).map({True: 'yes', False: 'no'})
  • (target_cols != 'no').any(axis=1)判断每行是否存在非'no'的列,返回布尔值
  • map方法直接将布尔值转换为需求的字符串结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:35:20