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

方形DataFrame元素行内移位需求:移除NaN后左对齐元素

解决方案

输入DataFrame

ABCD
102010050
NaN324563
NaNNaN75998
NaNNaNNaN32

期望输出

ABCD
102010050
324563NaN
75998NaNNaN
32NaNNaNNaN

实现代码

用numpy结合pandas可以高效完成需求,避免逐行循环的性能损耗:

import pandas as pd
import numpy as np

# 构造输入DataFrame(实际场景替换为你的数据)
df = pd.DataFrame({
    'A': [10, np.nan, np.nan, np.nan],
    'B': [20, 32, np.nan, np.nan],
    'C': [100, 45, 759, np.nan],
    'D': [50, 63, 98, 32]
})

# 核心处理逻辑
processed_df = pd.DataFrame(
    [row[~np.isnan(row)] for row in df.values],
    index=df.index
).reindex(columns=df.columns)

代码说明

  • row[~np.isnan(row)]:过滤每行的NaN值,仅保留有效数据
  • pd.DataFrame(...):用过滤后的行数据构造临时DataFrame
  • reindex(columns=df.columns):按照原DataFrame的列名重新索引,缺失的列位置自动填充NaN,完美匹配需求格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:22:42