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

如何优化Pandas代码合并DataFrame同组列并解决排序与空值问题

合并Pandas同前缀列并优化列顺序与分隔符

原DataFrame定义

import pandas as pd

df = pd.DataFrame({
    'name_1': ['Juan', '', ''],
    'name_2': ['', 'Pedro', ''],
    'name_3': ['', '', 'Ana'],
    'l_name': ['García', 'Sánchez', 'Hernández'],
    'profession_4': ['Doctor', 'Doctor', ''], 
    'profession_5': ['', '', 'architect'],
    'hobbie_6': ['Dance', '', 'Music'],
    'hobbie_7': ['', 'Music', 'Paint'],
    'hobbie_8': ['', '', 'Dance'],
})

原代码及存在的问题

原尝试的代码如下:

# Group the columns by their name before the underscore
grouped_columns = df.columns.to_series().groupby(lambda x: x.rsplit('_', 1)[0]).apply(list).tolist()

# Iterate through each group of columns and combine them
for columns in grouped_columns:
    # Get the name of the group
    group_name = columns[0].rsplit('_', 1)[0]
    # Combine the columns into a new column with the name of the group
    df[group_name + '_combined'] = pd.concat([df[column] for column in columns], axis=1).apply(lambda x: '/'.join(x.dropna().astype(str)), axis=1)
    
# Drop the original columns
df.drop(df.filter(regex='_\d+$').columns, axis=1, inplace=True)

# Display the resulting DataFrame
df

运行后存在两个问题:

  • 合并后的列顺序混乱,未遵循原DataFrame中前缀的出现顺序
  • 原数据中的空字符串''不会被dropna()识别,导致合并后出现多余的/分隔符

优化后的代码

import pandas as pd

df = pd.DataFrame({
    'name_1': ['Juan', '', ''],
    'name_2': ['', 'Pedro', ''],
    'name_3': ['', '', 'Ana'],
    'l_name': ['García', 'Sánchez', 'Hernández'],
    'profession_4': ['Doctor', 'Doctor', ''], 
    'profession_5': ['', '', 'architect'],
    'hobbie_6': ['Dance', '', 'Music'],
    'hobbie_7': ['', 'Music', 'Paint'],
    'hobbie_8': ['', '', 'Dance'],
})

# 1. 提取列前缀并保持原顺序(去重),确保分组顺序和原列前缀出现顺序一致
prefixes = []
for col in df.columns:
    prefix = col.rsplit('_', 1)[0] if '_' in col else col
    if prefix not in prefixes:
        prefixes.append(prefix)

# 2. 按前缀分组处理列
for prefix in prefixes:
    # 获取当前前缀对应的所有列
    if '_' in prefix:
        # 处理带数字后缀的前缀(如name、profession)
        group_cols = [col for col in df.columns if col.startswith(f"{prefix}_")]
    else:
        # 处理无数字后缀的列(如l_name)
        group_cols = [prefix]
    
    if len(group_cols) > 1:
        # 合并列:过滤空字符串后再join,避免多余分隔符
        df[f"{prefix}_combined"] = df[group_cols].apply(
            lambda row: '/'.join([val for val in row if val.strip() != '']),
            axis=1
        )
    else:
        # 单列直接保留,重命名为统一格式
        df[f"{prefix}_combined"] = df[group_cols[0]]

# 3. 删除原带数字后缀的列
df = df.drop(columns=[col for col in df.columns if '_' in col and col.split('_')[-1].isdigit()])

# 4. 调整列顺序:按照prefixes的顺序排列合并后的列
final_cols = [f"{p}_combined" for p in prefixes]
df = df[final_cols]

print(df)

优化说明

  • 解决列顺序问题:通过遍历原列提取前缀并去重,保证分组和最终列的顺序和原DataFrame中前缀首次出现的顺序一致,最后再按该顺序重新排列列。
  • 解决多余分隔符问题:替换dropna()为直接过滤空字符串(val.strip() != ''),因为原数据中的空值是''而非NaN,这样只保留有效非空值后再用/连接,不会产生多余分隔符。
  • 额外处理了无数字后缀的列(如l_name),统一命名为{prefix}_combined格式,保持列名风格一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:05:32