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

在Pandas DataFrame中标记指定月份列是否存在≥2的值

解决Pandas DataFrame多周期月份列的标记生成问题

需求说明

我是Python新手,需要在Pandas DataFrame中对代表月份的多列进行对比,判断每行在指定x个月周期内是否曾出现≥2的值,并生成标记:

  • 1表示存在≥2的值
  • 0表示所有值均<2
  • -1表示存在缺失数据(已将NaN值设为-1)

示例DataFrame生成代码

import numpy as np
import pandas as pd

arr_random = np.random.randint(low=0, high=5, size=(100,26))
col_names = []
i = 0
while i <= 25:
    col_names.append('mth_'+str(i))
    i = i + 1
rand_df = pd.DataFrame(arr_random, index = None, columns = col_names)

原标记生成代码(存在问题)

review_months = [12, 18, 24]
for x in review_months:
    rand_df['TWOPLUS_'+str(x)+'M'] = -1
    for i in range(x): 
        rand_df['TWOPLUS_'+str(x)+'M'] = rand_df[['TWOPLUS_'+str(x)+'M', 'mth_'+str(i+1)]].max(axis = 1)
        conditions  = [ rand_df['TWOPLUS_'+str(x)+'M'] >= 2, rand_df['TWOPLUS_'+str(x)+'M'] < 2, rand_df['mth_'+str(i)] == -1 ]
        choices     = [ 1 , 0, -1 ]
        rand_df['TWOPLUS_'+str(x)+'M'] = np.select(conditions, choices, default=np.nan)

问题分析

当前代码通过循环逐列更新标记,每次迭代都会覆盖之前的结果,无法累积判断整个x个月周期内是否出现过≥2的值,仅能反映当前遍历列的状态,不符合需求。

优化后的解决方案

利用Pandas行级聚合操作,一次性判断整行在指定周期内的状态,按优先级生成标记:

import numpy as np
import pandas as pd

# 生成带缺失值的示例DataFrame(模拟业务场景)
arr_random = np.random.randint(low=0, high=5, size=(100,26))
# 随机插入10%的缺失值(设为-1)
mask = np.random.choice([True, False], size=arr_random.shape, p=[0.1, 0.9])
arr_random[mask] = -1

col_names = [f'mth_{i}' for i in range(26)]
rand_df = pd.DataFrame(arr_random, columns=col_names)

review_months = [12, 18, 24]

for x in review_months:
    # 选取当前周期对应的月份列
    period_cols = [f'mth_{i}' for i in range(x)]
    # 判断每行是否存在缺失值(-1)
    has_missing = rand_df[period_cols].eq(-1).any(axis=1)
    # 判断每行是否存在≥2的值
    has_two_plus = rand_df[period_cols].ge(2).any(axis=1)
    
    # 按优先级生成标记:缺失优先→存在≥2→全部<2
    rand_df[f'TWOPLUS_{x}M'] = np.where(has_missing, -1,
                                        np.where(has_two_plus, 1, 0))

代码说明

  • eq(-1).any(axis=1):检查每行在指定周期列中是否有-1(缺失值),返回布尔序列
  • ge(2).any(axis=1):检查每行在指定周期列中是否有≥2的值,返回布尔序列
  • np.where嵌套:先判断缺失值(最高优先级)标记为-1,再判断是否有≥2的值标记为1,剩余情况标记为0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:00:24