简体   繁体   English

在 Pandas 中使用替换同时填充和填充

[英]ffill and bfill at same time using replace in Pandas

Question

Is there a way to ffill and bfill at the same time using replace in Pandas?有没有办法在 Pandas 中使用replace同时ffillbfill

See the following example :请参阅以下示例

l = 12
rng = pd.date_range('1/1/2011', periods=l, freq='8h')
df = pd.DataFrame({ 
    'animals':[0,0,'cat',0,'dog',0,0,0,'mouse',0,'ant',0],
    },index=rng)

df
Out[93]:
                  animals
2011-01-01 00:00:00 0
2011-01-01 08:00:00 0
2011-01-01 16:00:00 cat
2011-01-02 00:00:00 0
2011-01-02 08:00:00 dog
2011-01-02 16:00:00 0
2011-01-03 00:00:00 0
2011-01-03 08:00:00 0
2011-01-03 16:00:00 mouse
2011-01-04 00:00:00 0
2011-01-04 08:00:00 ant
2011-01-04 16:00:00 0

Im currently doing this using two iterations of replace .我目前使用replace两次迭代来执行此操作。

df.animals = df.groupby(df.index.to_datetime().day).transform(lambda x: x.replace(to_replace=0, method='ffill'))
df.animals = df.groupby(df.index.to_datetime().day).transform(lambda x: x.replace(to_replace=0, method='bfill'))

df

                  animals
2011-01-01 00:00:00 cat
2011-01-01 08:00:00 cat
2011-01-01 16:00:00 cat
2011-01-02 00:00:00 dog
2011-01-02 08:00:00 dog
2011-01-02 16:00:00 dog
2011-01-03 00:00:00 mouse
2011-01-03 08:00:00 mouse
2011-01-03 16:00:00 mouse
2011-01-04 00:00:00 ant
2011-01-04 08:00:00 ant
2011-01-04 16:00:00 ant
    ​

It works ok but I thought there may be a way to ffill and bfill so thought worth checking on SO.它工作正常,但我认为可能有一种方法来ffillbfill所以认为值得检查一下。

IIUC you can do it this way: IIUC 你可以这样做:

In [278]: df['animals'] = df['animals'].replace(0, np.nan) \
                                       .groupby(pd.TimeGrouper('D')) \
                                       .bfill().ffill()

In [279]: df
Out[279]:
                    animals
2011-01-01 00:00:00     cat
2011-01-01 08:00:00     cat
2011-01-01 16:00:00     cat
2011-01-02 00:00:00     dog
2011-01-02 08:00:00     dog
2011-01-02 16:00:00     dog
2011-01-03 00:00:00   mouse
2011-01-03 08:00:00   mouse
2011-01-03 16:00:00   mouse
2011-01-04 00:00:00     ant
2011-01-04 08:00:00     ant
2011-01-04 16:00:00     ant

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM