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

如何拼接首有效索引不同的Pandas列得到连续的单列数据

实现方案

首先确保已经导入依赖库:

import pandas as pd
import numpy as np

方法1:最简实现(适配你的场景)

你的需求本质是对每行取从左到右(A到F顺序)第一个非缺失值,直接用列方向后向填充取首列即可:

res = df.bfill(axis=1).iloc[:, [0]]
res.columns = ['A']

方法2:按列接续规则实现(严格匹配你描述的逻辑)

如果严格按照「前一列有效值结束后,下一列从结束索引位置开始接续」的规则编写,代码如下:

cols = df.columns.tolist()
result = pd.Series(dtype='float64')

last_idx = -1
for col in cols:
    # 取当前列最后一个有效值的索引
    curr_last_idx = df[col].last_valid_index()
    if pd.isna(curr_last_idx):
        continue
    # 截取当前列需要拼接的片段
    part = df.loc[last_idx + 1 : curr_last_idx, col]
    result = pd.concat([result, part])
    last_idx = curr_last_idx

# 转为DataFrame格式
res = result.to_frame('A')

两种方法输出的结果均和你给出的预期一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:45:05