前向填充python pandas数据帧中除最后一个值 [英] Forward fill all except last value in python pandas dataframe

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

问题描述

我在 Pandas 中有一个数据框,其中有几列我想转发填充值.目前我正在做:

I have a dataframe in pandas with several columns I want to forward fill the values for. At the moment I'm doing:

columns = ['a', 'b', 'c']
for column in columns:
    df[column].fillna(method='ffill', inplace=True)

...但是因为列中的系列长度不同,所以在其中一些的末端留下填充值的长尾.由于某些系列中的差距非常大,因此我无法使用 fillna 的限制参数,同时也会在系列上留下填充值的长尾.

...but because the series in the columns are different lengths, that leaves long tails of filled values on the ends of some of them. Because the gaps in the some of the series are quite large, I can't use the fillna's limit parameter without also leaving long tails of filled values on the series.

是否可以向前填充每列中的值,最后一个值除外?谢谢!

Is it possible to forward fill the values in each columns, except the last value? Thanks!

推荐答案

您可以在 lambda 函数中使用 last_valid_index 来填充到那个点.

You can use last_valid_index in a lambda function to just ffill up to that point.

df = pd.DataFrame({
    'A': [1, None, None, None], 
    'B': [1, 2, None, None], 
    'C': [1, None, 3, None], 
    'D': [1, None, None, 4]})

>>> df
    A   B   C   D
0   1   1   1   1
1 NaN   2 NaN NaN
2 NaN NaN   3 NaN
3 NaN NaN NaN   4

>>> df.apply(lambda series: series.loc[:series.last_valid_index()].ffill())
    A   B   C  D
0   1   1   1  1
1 NaN   2   1  1
2 NaN NaN   3  1
3 NaN NaN NaN  4

这篇关于前向填充python pandas数据帧中除最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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