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

Pandas按列名后缀拆分DataFrame后沿另一轴拼接的实现方法

Pandas 列名按尾部分组后行拼接解决方案

直接使用以下代码即可完成需求,该方案适配任意长度的列名前缀:

import pandas as pd

# -------------------- 以下为示例数据构造,实际使用时替换为你的DataFrame --------------------
df = pd.DataFrame({
    'A1': [1,2,3], 'B1': [2,4,2], 'C1': [4,3,5], 'D1': [2,5,2], 'E1': [3,3,6], 'F1': [2,2,7],
    'A2': [5,2,3], 'B2': [3,3,5], 'C2': [2,2,3], 'D2': [0,2,2], 'E2': [3,4,5], 'F2': [1,1,1]
})
# -----------------------------------------------------------------------------------------

# 提取结尾为1的列,并重命名为去掉尾部1的前缀
df_suffix1 = df.loc[:, df.columns.str.endswith('1')]
df_suffix1.columns = df_suffix1.columns.str.rstrip('1')

# 提取结尾为2的列,并重命名为去掉尾部2的前缀
df_suffix2 = df.loc[:, df.columns.str.endswith('2')]
df_suffix2.columns = df_suffix2.columns.str.rstrip('2')

# 沿行方向拼接两个子集,ignore_index=True会重置行索引,不需要可删除该参数
result = pd.concat([df_suffix1, df_suffix2], ignore_index=True)

执行后result即为符合要求的输出结果。

内容的提问来源于stack exchange,提问作者8-Bit Borges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:24:00