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

如何筛选pandas DataFrame:从开头到首个非NaN行及从该行到末尾

Pandas DataFrame 两种筛选操作实现

首先先构造你的示例DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'number': [12, 13, 14, 15, 16, 17, 18],
    'score': [np.nan, np.nan, np.nan, np.nan, 10, np.nan, np.nan]
})

1. 筛选起始行到score列首次出现数值的行(包含该行)

先获取score列第一个非缺失值的索引:

first_valid_idx = df['score'].first_valid_index()

然后通过索引切片得到目标DataFrame:

new_df1 = df.loc[:first_valid_idx]

运行后new_df1结果如下:

number  score
0      12    NaN
1      13    NaN
2      14    NaN
3      15    NaN
4      16   10.0

2. 筛选score列首次出现数值的行到末尾的所有行

直接用第一步得到的索引切片到末尾:

new_df2 = df.loc[first_valid_idx:]

运行后new_df2结果如下:

number  score
4      16   10.0
5      17    NaN
6      18    NaN

说明:first_valid_index()是Pandas专门用来获取列中第一个非缺失值索引的方法,配合loc的切片语法可以快速实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:16:05