如何基于指定条件规则为pandas DataFrame填充新列
Pandas按指定规则填充新列解决方案
你可以直接用pandas内置的isin()方法配合条件判断实现需求,完全基于你已经提取好的参数,无需硬编码规则,两种常用实现方式如下:
方法1:使用numpy的where函数(逻辑更直观)
import pandas as pd import numpy as np # 你已提取的参数 options = ['Type A', 'Type B', 'Type C'] col_to_check = 'Game' value_if_met = 'Played' else_use_col = 'Status' new_col_name = 'Result' # 示例DataFrame df = pd.DataFrame( { 'ID': ['AB01', 'AB02', 'AB03', 'AB04', 'AB05','AB06'], 'Game': ['Type A','Type B','Type A','Type C','Type D','Type D'], 'Status': ['Won', 'Draw', 'Won', np.nan, 'Won',np.nan] } ) # 核心逻辑:匹配成功赋值指定值,失败取对应Status列的值 df[new_col_name] = np.where(df[col_to_check].isin(options), value_if_met, df[else_use_col])
方法2:使用pandas的where方法(更贴合原生pandas语法)
# 先默认全赋值为匹配成功的结果 df[new_col_name] = value_if_met # 不满足匹配条件的位置替换为Status列的值 df[new_col_name] = df[new_col_name].where(df[col_to_check].isin(options), df[else_use_col])
运行后得到的Result列完全符合预期输出:['Played','Played','Played','Played','Won',np.nan],会自动保留Status列的nan值无需额外处理。
内容的提问来源于stack exchange,提问作者Zakyl
相关产品推荐
相关产品推荐

