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

Pandas:合并DataFrame列后将列名添加至行并设置加粗

问题:DataFrame多列合并并添加带格式的列名前缀

现有如下DataFrame:

import pandas as pd

df1 = pd.DataFrame({'ID'    : ['T1002.', 'T5006.', 'T5007.'],
                    'Parent': ['Stay home.', "Stay home.","Stay home."],
                    'Child' : ['2Severe weather.', "5847.", "Severe weather."]})

其结构为:

ID      Parent       Child
0   T1002.  Stay home.  2Severe weather.
1   T5006.  Stay home.  5847.
2   T5007.  Stay home.  Severe weather.

需求是将多列合并为一列,每段内容前加上加粗格式的列名(如**ID**: ),预期输出如下:

Joined_columns
0   **ID**: T1002.  **Parent**: Stay home.   **Child**: 2Severe weather.
1   **ID**: T5006.  **Parent**: Stay home.   **Child**: 5847.
2   **ID**: T5007.  **Parent**: Stay home.   **Child**: Severe weather.

目前已尝试以下代码,但未实现列名前缀的添加:

df1_final=df1.stack().groupby(level=0).apply(' '.join).to_frame(0)

解决思路

方法1:逐行拼接(直观易读)

直接遍历每行的列名与对应值,拼接成**列名**: 值的格式后用空格连接:

def join_cols(row):
    return '  '.join([f'**{col}**: {row[col]}' for col in df1.columns])

df1['Joined_columns'] = df1.apply(join_cols, axis=1)
df1_final = df1[['Joined_columns']]

该方法逻辑简单,适合小数据集快速实现需求。

方法2:向量化操作(高效处理大数据)

避免逐行apply的性能损耗,先给每列批量添加前缀,再合并:

# 给每列的所有值添加带格式的列名前缀
prefixed_cols = [f'**{col}**: ' + df1[col].astype(str) for col in df1.columns]

# 合并所有列,用两个空格分隔内容
df1_final = pd.concat(prefixed_cols, axis=1).apply('  '.join, axis=1).to_frame('Joined_columns')

此方式利用Pandas向量化特性,处理大规模数据时效率更高。

方法3:基于现有stack代码改进

如果想沿用你已有的stack思路,只需在stack前先给每个元素加上列名前缀:

# 先为每个元素拼接列名前缀
df_with_prefix = df1.apply(lambda x: f'**{x.name}**: {x}')

# 再执行stack分组合并
df1_final = df_with_prefix.stack().groupby(level=0).apply('  '.join).to_frame('Joined_columns')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:55:30