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

Pandas统计同一行与2019_5列值相同的出现次数及连续性判断

实现代码

首先按时间顺序指定要统计的年份列(顺序不能乱,会影响连续判断逻辑),完整实现如下:

import pandas as pd
import numpy as np

# 按时间先后指定统计列,有新增年份直接修改这个列表即可
year_cols = ['2015_5', '2016_5', '2017_5', '2018_5', '2019_5']

# 1. 计算number_yrs:统计每行和2019_5取值相等的单元格数量
df['number_yrs'] = df[year_cols].eq(df['2019_5'], axis=0).sum(axis=1)

# 2. 自定义函数判断匹配值是否连续
def check_continuous(row):
    match_cnt = row['number_yrs']
    # 匹配数<=1时直接返回n,符合输出要求
    if match_cnt <= 1:
        return 'n'
    # 收集所有匹配值的位置索引
    match_pos = [idx for idx, val in enumerate(row[year_cols]) if val == row['2019_5']]
    # 最大索引-最小索引+1等于匹配数说明中间无断开,是连续序列
    return 'y' if (max(match_pos) - min(match_pos) + 1 == match_cnt) else 'n'

df['continuous'] = df.apply(check_continuous, axis=1)

# 提取最终输出列
result = df[['member', 'number_yrs', 'continuous']]

结果验证

运行后输出的result和你给出的预期完全一致:

member  number_yrs continuous
0    aaa           1          n
1    bbb           5          y
2    ccc           3          n
3    ddd           2          y
4    eee           2          n

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:36:10