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

如何在Pandas DataFrame中逐行执行函数并合并指定行?

解决Pandas中基于自定义函数合并行的需求

需求说明

给定如下结构的DataFrame:

textnumber
hello a b c12
text c d e13
hello z b c45
small type36

存在自定义函数calc,接收两个字符串返回数字。要求遍历所有行,当calc(当前行text, 下一行text)返回1时,将下一行的number值累加到当前行的number中,并删除下一行。

实现方案

可以通过while循环逐行判断的方式处理,避免因删除行导致的索引混乱问题,代码示例如下:

1. 构造示例数据与自定义函数

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'text': ['hello a b c', 'text c d e', 'hello z b c', 'small type'],
    'number': [12, 13, 45, 36]
})

# 示例calc函数,仅对第1、2行的text组合返回1
def calc(s1, s2):
    if s1 == 'hello a b c' and s2 == 'text c d e':
        return 1
    return 0

2. 核心处理逻辑

i = 0
while i < len(df) - 1:
    # 获取当前行与下一行的text
    current_text = df.iloc[i]['text']
    next_text = df.iloc[i+1]['text']
    
    if calc(current_text, next_text) == 1:
        # 累加下一行的number到当前行
        df.loc[i, 'number'] += df.iloc[i+1]['number']
        # 删除下一行
        df = df.drop(df.index[i+1])
    else:
        # 无需合并,移动到下一行
        i += 1

3. 验证结果

执行上述代码后,打印df会得到目标结果:

text  number
0  hello a b c      25
1  hello z b c      45
2    small type      36

注意事项

  • 该方法支持连续多行合并的场景(例如calc对行1-2、行2-3均返回1),因为合并后i不会递增,下一次循环会继续检查当前行与新的下一行。
  • 使用while循环而非for循环,是因为删除行后DataFrame长度动态变化,for循环的固定索引会导致遍历遗漏或错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:39:45