You need to enable JavaScript to run this app. pandas DataFrame删除指定值后剩余值上移的无列表中间件实现
优惠活动
大模型
产品
解决方案
定价
更多

pandas DataFrame删除指定值后剩余值上移的无列表中间件实现

需求说明

我有一个存储分类数据的pandas DataFrame,已实现仅保留selecList指定分类、删除其余值后将剩余值向上对齐空位的逻辑,但现有实现用到了列表作为中间处理环节,希望找到无需列表中间件的实现方案。

示例数据

import pandas as pd
mydf = pd.DataFrame(data = {'a': [9,6,3,8,5], 
                            'b': [4, 3,5,6,7], 
                            'c': [5, 3,6,9,10]
                           } 
                    )

selecList = [5,8,4,6] # 仅保留该列表内的分类值

原始DataFrame输出:

a  b   c
0  9  4   5
1  6  3   3
2  3  5   6
3  8  6   9
4  5  7  10

预期输出

a   b   c
0   6   4   5
1   8   5   6
2   5   6   <NA>

现有实现方案(使用列表中间件)

myList = mydf.T.values.tolist()
filtered_list = [[x for x in y if x in selecList ] for y in myList] 
filtered_df = pd.DataFrame(filtered_list).T
filtered_df.columns = list(mydf)
filtered_df = filtered_df.astype('Int64')

未成功尝试

pd.DataFrame(mydf.apply(lambda y: [x for x in y if x in selecList ])).T

无列表中间件的实现方案

全程基于pandas原生方法操作,无需将DataFrame转换为Python列表作为中间过渡:

# 替换非目标分类值为NaN
tmp = mydf.where(mydf.isin(selecList))
# 逐列删除空值后对齐索引拼接
res = pd.concat(
    [tmp[col].dropna().reset_index(drop=True) for col in tmp.columns],
    axis=1
).astype('Int64')

方案说明

  • 用DataFrame.isin匹配目标分类值,配合where方法将非目标值批量替换为NaN,全程在pandas二维表结构内完成
  • 对每列执行dropna()删除空值后调用reset_index(drop=True),剩余值会自动从行索引0开始排列,实现「剩余值向上填充空位」的对齐效果
  • 最后用pd.concat按列拼接所有处理后的序列,转换为可空整型Int64,输出结果和预期完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 02:06:04