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

如何遍历Pandas稀疏Series并跳过缺失值?

获取Pandas稀疏Series非空值的对应索引

方法1:布尔索引筛选原Series索引

直接通过判断值是否等于填充值,筛选出目标索引,这是最稳妥的通用方法:

import pandas as pd

a = pd.Series([2, 3, 0, 0, 4], dtype='Sparse[int]')
non_null_indices = a[a != a.sparse.fill_value].index.tolist()
print(non_null_indices)  # 输出: [0, 1, 4]

方法2:访问SparseArray的indices属性

虽然a.sparse.sp_index报错,但可以直接访问Series底层SparseArray的indices属性:

non_null_indices = a.array.indices.tolist()
print(non_null_indices)  # 输出: [0, 1, 4]

注意:该方法依赖Pandas内部实现,不同版本可能存在兼容性问题,优先推荐方法1。

方法3:遍历非空值时同步获取索引

如果你的核心需求是遍历非空值并跳过缺失值,可直接在遍历过程中判断并获取索引:

for idx, val in a.items():
    if val != a.sparse.fill_value:
        print(f"索引: {idx}, 值: {val}")
# 输出结果:
# 索引: 0, 值: 2
# 索引: 1, 值: 3
# 索引: 4, 值: 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:30:37