pandas :仅在数据框的开头和结尾处删除NaN [英] Pandas: Remove NaN only at beginning and end of dataframe

查看:47
本文介绍了 pandas :仅在数据框的开头和结尾处删除NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的pandas DataFrame:

I've got a pandas DataFrame that looks like this:

       sum
1948   NaN
1949   NaN
1950     5
1951     3
1952   NaN
1953     4
1954     8
1955   NaN

,我只想在开头和结尾处截断 (即应该只保留从1950年到1954年的值,包括)..我已经尝试过 .isnull() dropna(),但是以某种方式我找不到合适的解决方案.有人可以帮忙吗?

and I would like to cut off the NaNs at the beginning and at the end ONLY (i.e. only the values incl. NaN from 1950 to 1954 should remain). I already tried .isnull() and dropna(), but somehow I couldn't find a proper solution. Can anyone help?

推荐答案

使用内置的

Use the built in first_valid_index and last_valid_index they are designed specifically for this and slice your 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

这篇关于 pandas :仅在数据框的开头和结尾处删除NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆