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

如何在Pandas中合并DataFrame中拆分到多行的描述文本?

问题描述

我有一个格式存在问题的Pandas DataFrame,原始数据如下:

id                  sub      status      description
313                 AF       open        test
234                 JF       open        testing in progress
919                 IA       closed      test
is completed
                 well done
393                 QE        open       failed testing
888                 VE        open       check the
test results
before closing
193                 UR        open       waiting

部分description字段的内容被拆分到新行中,需要将这些分散的文本合并回对应原始行,期望结果如下:

id                  sub      status      description
313                 AF       open        test
234                 JF       open        testing in progress
919                 IA       closed      test is completed well done
393                 QE       open        failed testing
888                 VE       open        check the test results before closing
193                 UR       open        waiting

另外,读取后id列的数据如下:

0     NaN
1     NaN
2     NaN
3     NaN
4     NaN
5     NaN
6     0.0
7     0.0
8     0.0
9     0.0
10    0.0
11    NaN
12    NaN
13    NaN
14    NaN
15    0.0
16    0.0
17    0.0
18    NaN
19    NaN
20    0.0
21    0.0
22    0.0
23    0.0

Name: id, dtype: object

请问如何在Pandas中实现这一需求?

解决方案

可以通过分组标识、文本合并、数据清理三步完成修复:

  1. 标记分组:以带有有效数字id的行为分组起点,向下填充分组标识,让拆分出来的行归属到对应的原始行组。
  2. 合并文本:遍历每个分组,收集所有分散在id、sub、description列中的文本片段,合并成完整的description内容。
  3. 整合数据:提取原始有效行的id、sub、status信息,与合并后的description关联,得到最终修复后的DataFrame。

代码实现

import pandas as pd

# 假设数据已读取到df中(可根据实际读取方式调整,比如pd.read_csv)
# 1. 创建分组标识:仅保留有效数字id作为分组键,向下填充
df['group'] = df['id'].apply(lambda x: x if pd.notna(x) and str(x).isdigit() else None)
df['group'] = df['group'].ffill()

# 2. 自定义函数:合并分组内所有文本片段
def merge_description(group):
    text_parts = []
    for _, row in group.iterrows():
        # 收集id列中的无效数字文本
        if pd.notna(row['id']) and not str(row['id']).isdigit():
            text_parts.append(str(row['id']))
        # 收集sub列中的非标准代码文本(假设原始sub为两位字符)
        if pd.notna(row['sub']) and len(str(row['sub'])) > 2:
            text_parts.append(str(row['sub']))
        # 收集description列的内容
        if pd.notna(row['description']):
            text_parts.append(str(row['description']))
    return ' '.join(text_parts)

# 按分组聚合合并后的description
merged_descriptions = df.groupby('group').apply(merge_description).reset_index(name='description')

# 3. 提取有效行的基础数据(id/sub/status)
valid_base_data = df[df['id'].astype(str).isdigit()].drop(columns=['description', 'group'])

# 合并基础数据与修复后的description
final_df = valid_base_data.merge(merged_descriptions, left_on='id', right_on='group').drop(columns=['group'])

# 重置索引
final_df = final_df.reset_index(drop=True)

print(final_df)

注意事项

  • 如果id列的有效数字被识别为浮点数(如313变为313.0),可先转换处理:df['id'] = df['id'].astype(str).str.replace('.0', '', regex=False)
  • 若sub列的合法格式不是两位字符,需调整代码中len(str(row['sub'])) > 2的判断条件,比如改为检查是否在预设的合法sub列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:35:39