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

比较长度不同的pd.Series并筛选符合要求的差异值及额外值

不等长Pandas Series按规则比较实现方案

首先给出可直接运行的代码,输出结果完全匹配你的预期:

import pandas as pd

# 初始化两个Series
one = pd.Series([536, 1226, 2370, 2996, 10256, 10592])
two = pd.Series([812, 1172, 2639, 3157])

# 对齐两个Series长度,缺失值填充为NaN
max_len = max(len(one), len(two))
one_align = one.reindex(range(max_len))
two_align = two.reindex(range(max_len))

# 初始化结果存储容器
one_greater = []
two_match = []
extra_one = []
extra_two = []

for i in range(max_len):
    o_val = one_align.iloc[i]
    t_val = two_align.iloc[i]
    # 处理两个位置都有值的公共区间
    if pd.notna(o_val) and pd.notna(t_val):
        diff = o_val - t_val
        # 按规则匹配:one大于two时记录对应值,其余情况标记为we good直接跳过
        if diff > 0:
            one_greater.append(str(int(o_val)))
            two_match.append(str(int(t_val)))
    # 处理one多出来的额外值
    elif pd.notna(o_val) and pd.isna(t_val):
        extra_one.append(str(int(o_val)))
    # 处理two多出来的额外值(当前示例没有该场景,代码兼容该情况)
    elif pd.isna(o_val) and pd.notna(t_val):
        extra_two.append(str(int(t_val)))

# 按要求拼接输出结果
res_parts = []
if one_greater:
    res_parts.append(f"one({','.join(one_greater)})")
if two_match:
    res_parts.append(f"two({','.join(two_match)})")
if extra_one:
    res_parts.append(f"one({','.join(extra_one)})")
if extra_two:
    res_parts.append(f"two({','.join(extra_two)})")

print(" and ".join(res_parts))

运行上述代码后输出结果为:
one(1226) and two(1172) and one(10256,10592)
完全符合预期。
实现逻辑说明:

  • 先通过reindex对齐两个Series的长度,避免因为长度不一致导致的索引匹配错误
  • 逐行遍历每个对齐后的位置,分别处理公共长度区间、长序列额外值区间的逻辑
  • 最后把收集到的符合要求的结果按格式拼接即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:57:02