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

如何在Pandas中逐行判断DataFrame列内整数列表是否连续?

问题解决:Pandas Series.apply 报错原因及修正

错误原因

你报错的核心问题是:df['a']是Series对象,而Series.apply()方法并不接受axis参数——axis是DataFrame的apply()方法才需要的参数。当你给Series的apply传axis=1时,就会触发参数错误。

修正后的代码

只需要去掉axis=1即可正常运行:

import pandas as pd

df = pd.DataFrame({'a': [[0,2], [9,11,12], [0,1,2], [10,11,13]]})

def cons(L):
    return all(n - i == L[0] for i, n in enumerate(L))

print(cons(df['a'][0]))  # 输出: False

df['cons'] = df['a'].apply(cons)  # 去掉axis=1参数
print(df)

运行结果

a   cons
0        [0, 2]  False
1   [9, 11, 12]  False
2     [0, 1, 2]   True
3  [10, 11, 13]  False

可选优化:兼容乱序的连续列表判断

如果你的列表可能是乱序的(比如[2,0,1]),原函数会误判为False。可以修改判断逻辑,通过「最大值-最小值+1等于列表长度,且元素无重复」来准确判断:

def cons(L):
    if not L:
        return False  # 处理空列表的边界情况
    return len(set(L)) == len(L) and (max(L) - min(L) + 1) == len(L)

# 测试乱序连续列表
print(cons([2,0,1]))  # 输出: True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:04:54