Python 删除表中2个特定列之间的空值

Python 删除表中2个特定列之间的空值,python,pandas,Python,Pandas,我有以下时间序列数据帧。我想用前面的值来填充缺少的值。但是,我只想填充第一个有效索引和最后一个有效索引之间缺少的值。因此,我要填充的列对于每一行都是不同的。我该怎么做 所以,给定这个数据帧 import numpy as np import pandas as pd df = pd.DataFrame([[1, 2 ,3,np.nan,5], [1, 3 , np.nan , 4 , np.nan], [4, np.nan , 7 , np.nan,np.nan]], columns=[2007

我有以下时间序列数据帧。我想用前面的值来填充缺少的值。但是,我只想填充第一个有效索引和最后一个有效索引之间缺少的值。因此,我要填充的列对于每一行都是不同的。我该怎么做

所以,给定这个数据帧

import numpy as np
import pandas as pd
df = pd.DataFrame([[1, 2 ,3,np.nan,5], [1, 3 , np.nan , 4 , np.nan], [4, np.nan , 7 , np.nan,np.nan]], columns=[2007,2008,2009,2010,2011])
输入数据帧:

    2007    2008    2009    2010    2011
     1       2       3      NaN     5
     1       3       NaN    4       NaN
     4       Nan     7      NaN     NaN     
2007    2008    2009    2010    2011
 1       2       3        3      5
 1       3       3        4      NaN
 4       4       7        NaN    NaN
输出数据帧:

    2007    2008    2009    2010    2011
     1       2       3      NaN     5
     1       3       NaN    4       NaN
     4       Nan     7      NaN     NaN     
2007    2008    2009    2010    2011
 1       2       3        3      5
 1       3       3        4      NaN
 4       4       7        NaN    NaN
我想为第一个有效索引和最后一个有效索引创建新列,然后使用.apply(),但如何才能每行填充不同的列

def fillMissing(x):
    first_valid = int(x["first_valid"])
    last_valid = int(x["last_valid"])
    for i in range(first_valid,last_valid + 1):
        missing.append(i)
    #What should i do here since the following is not valid 
    #x[missing] = x[missing].fillna(method='ffill', axis=1)


df.apply(fillMissing , axis=1)

您可以使用
iloc
来实现这一点,但我更喜欢使用Numpy。基本上,使用
ffill
转发填充值,然后将
NaN
的值屏蔽到底

v = df.values

mask = np.logical_and.accumulate(
    np.isnan(v)[:, ::-1], axis=1)[:, ::-1]

df.ffill(axis=1).mask(mask)

   2007  2008  2009  2010  2011
0   1.0   2.0   3.0   3.0   5.0
1   1.0   3.0   3.0   4.0   NaN
2   4.0   4.0   7.0   NaN   NaN

这里有两个完全基于NumPy的,灵感来自-

对较大的
df
进行运行时测试,并填写
50%
NAN-

In [249]: df = pd.DataFrame(np.random.randint(1,9,(5000,5000)).astype(float))

In [250]: idx = np.random.choice(df.size, df.size//2, replace=0)

In [251]: df.values.ravel()[idx] = np.nan

# @piRSquared's soln
In [252]: %%timeit
     ...: v = df.values
     ...: mask = np.logical_and.accumulate(
     ...:     np.isnan(v)[:, ::-1], axis=1)[:, ::-1]
     ...: df.ffill(axis=1).mask(mask)
1 loop, best of 3: 473 ms per loop

In [253]: %timeit app1(df)
1 loop, best of 3: 353 ms per loop

In [254]: %timeit app2(df)
1 loop, best of 3: 330 ms per loop

我看不到您的表中的每一行都有不同的列example@GarbageCollector谢谢我编辑了这个例子。所以请注意我想在第一排的2007年和2011年之间填充。但我只想在2007年到2009年的第三排填上。