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

如何获取DataFrame中balance列含NaN值的行索引?

获取DataFrame中指定列含NaN值的行索引

针对你的需求,直接给几种高效的解决方法:

方法1:一步到位筛选并提取索引

直接对balance列做NaN判断,筛选出对应行后提取索引:

# 筛选balance列值为NaN的行,再获取索引
nan_indices = df[df['balance'].isnull()].index
print(nan_indices)

输出结果:Index(['user1', 'user2'], dtype='object')

方法2:基于你已有的代码优化

你已经得到了标记NaN的布尔Seriesdf3,直接筛选出值为True的项即可拿到索引:

df1 = df.isnull()
df3 = df1['balance']
# 提取df3中值为True的索引
nan_indices = df3[df3].index
print(nan_indices)

补充:为什么不能用== NaN?

NaN的特性是不等于任何值,包括它自己,所以df['balance'] == np.nan会返回全False的Series,永远得不到正确结果,必须用pandas提供的isnull()或isna()方法来判断NaN。

另外你从Stack Overflow找到的df = (df > 0).reindex(list(range(5)))和你的需求不匹配,所以无效,无需使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:10:16