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

如何在pandas DataFrame中移除NaN并左移值压缩数据以减少列数?

解决DataFrame移除NaN/None并左对齐非空值的问题

问题分析

你用dropna()没效果,是因为默认的dropna()逻辑是删除包含NaN的行或列,而非提取每行的非空值并重新左对齐排列。另外你的数据里混有None,dropna()默认不会识别处理object类型列里的None,所以需要先统一转换为NaN。

解决方案

按以下步骤处理:

  1. 导入依赖并模拟原始数据
import pandas as pd
import numpy as np

# 模拟你的原始DataFrame
data = [
    [5.29559, np.nan, 2.38176, np.nan, 0.51521, np.nan, 0.04454, 0.00000, None, None, None, None, None, None, None, None],
    [0, np.nan, np.nan, np.nan, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, 0, 2, None, None, None],
    [4.32454, np.nan, 1.77600, np.nan, 0.04454, np.nan, 0.00000, None, None, None, None, None, None, None, None, None],
    [0, np.nan, np.nan, np.nan, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, 2, None, None, None, None]
]
df = pd.DataFrame(data)
  1. 将None转换为NaN
    确保所有空值都能被dropna()识别:
df = df.replace({None: np.nan})
  1. 逐行提取非空值并左对齐
    对每行单独处理,移除NaN后重新索引,让非空值左对齐:
result_df = df.apply(lambda row: row.dropna().reset_index(drop=True), axis=1)

最终结果

运行上述代码后,result_df就会呈现你想要的样式:

0         1         2         3         4
0  5.29559  2.38176  0.51521  0.04454  0.00000
1  0.00000  0.00000  0.00000  0.00000  2.00000
2  4.32454  1.77600  0.04454  0.00000       NaN
3  0.00000  0.00000  0.00000  2.00000       NaN

(如果不需要末尾的NaN,可额外执行result_df = result_df.dropna(axis=1, how='all')删除全NaN列)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:42:22