pandas 在数据帧中向后插值() [英] Pandas interpolate() backwards in dataframe

查看:97
本文介绍了 pandas 在数据帧中向后插值()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

展望未来, 内插 效果很好:

Going forward, interpolate works great:

       name    days
0      a       NaN
1      a       NaN
2      a         2
3      a         3
4      a       NaN 
5      a       NaN  

records.loc[:, 'days'].interpolate(method='linear', inplace=True)

       name    days
0      a       NaN
1      a       NaN
2      a         2
3      a         3
4      a         4 
5      a         5  

...但是,它不处理开始的行(仅向前)。 limit_direction 参数允许 {前进,后退,两者} 。这些都不起作用。有没有适当的方法可以向后插值?

...however, it does not address the beginning rows (only goes forward). The limit_direction param allows {‘forward’, ‘backward’, ‘both’}. None of these works. Is there a proper way to interpolate backwards?

我们可以假设序列递增或递减1,但在本例中可能不会从0开始。 / p>

We can assume a series incrementing or decrementing by 1, which may not start at 0 as it happens to in this example.

推荐答案

似乎仅与参数 limit 一起使用,请参见文档[在47]

It seems it works only with parameter limit see docs [In 47]:


添加与 limit 一起使用的 limit_direction 关键字参数,以使插值能够向前填充NaN值,向后或两者(GH9218,GH10420,GH11115)

Add a limit_direction keyword argument that works with limit to enable interpolate to fill NaN values forward, backward, or both (GH9218, GH10420, GH11115)



records = pd.DataFrame(
{'name': {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'a', 5: 'a', 6: 'a', 7: 'a', 8: 'a', 9: 'a'}, 
'days': {0: 0.0, 1: np.nan, 2: np.nan, 3: np.nan, 4: 4.0, 5: 5.0, 6: np.nan, 7: np.nan, 8: np.nan, 9: 9.0}}, 
columns=['name','days'])

print (records)
  name  days
0    a   0.0
1    a   NaN
2    a   NaN
3    a   NaN
4    a   4.0
5    a   5.0
6    a   NaN
7    a   NaN
8    a   NaN
9    a   9.0





#by default limit_direction='forward'
records['forw'] = records['days'].interpolate(method='linear', 
                                              limit=1)
records['backw'] = records['days'].interpolate(method='linear',
                                               limit_direction='backward', 
                                               limit=1)
records['both'] = records['days'].interpolate(method='linear', 
                                              limit_direction='both', 
                                              limit=1)
print (records)
  name  days  forw  backw  both
0    a   0.0   0.0    0.0   0.0
1    a   NaN   1.0    NaN   1.0
2    a   NaN   NaN    NaN   NaN
3    a   NaN   NaN    3.0   3.0
4    a   4.0   4.0    4.0   4.0
5    a   5.0   5.0    5.0   5.0
6    a   NaN   6.0    NaN   6.0
7    a   NaN   NaN    NaN   NaN
8    a   NaN   NaN    8.0   8.0
9    a   9.0   9.0    9.0   9.0

这篇关于 pandas 在数据帧中向后插值()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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