Pandas:仅在数据帧的开头和结尾删除NaN

use*_*048 14 python time-series nan dataframe pandas

我有一个像这样的pandas DataFrame:

       sum
1948   NaN
1949   NaN
1950     5
1951     3
1952   NaN
1953     4
1954     8
1955   NaN
Run Code Online (Sandbox Code Playgroud)

我想NaN在开始和结束时切断s(即仅NaN保留1950至1954年的值).我已经尝试过.isnull()dropna(),但不知何故,我无法找到一个妥善的解决办法.有人可以帮忙吗?

EdC*_*ica 23

使用内置的first_valid_index,last_valid_index它们专门为此设计并切片你的df:

In [5]:

first_idx = df.first_valid_index()
last_idx = df.last_valid_index()
print(first_idx, last_idx)
df.loc[first_idx:last_idx]
1950 1954
Out[5]:
      sum
1950    5
1951    3
1952  NaN
1953    4
1954    8
Run Code Online (Sandbox Code Playgroud)