更改 pandas 轴以替换填充 [英] Change axis for pandas replace ffill

查看:88
本文介绍了更改 pandas 轴以替换填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个看起来像这样的数据框:

Suppose I have a dataframe that looks like:

df =
       0    1    2
  0  1.0  2.0  3.0
  1  4.0  5.0  NaN
  2  6.0  NaN  NaN

然后可以使用 df.fillna(method ='ffill',axis = 1)来获得:

     0    1    2
0  1.0  2.0  3.0
1  4.0  5.0  5.0
2  6.0  6.0  6.0

即我向前填充行。
但是,现在我有了一个 -1 的数据框,而不是 np.nan 。熊猫具有 replace 函数,该函数还可以使用 method ='ffill',但 replace()不接受轴参数,因此要获得与上述相同的结果,我需要调用 df.T.replace(-1,method =' ffill')。T 。由于转置非常昂贵(尤其是考虑到我正在处理多个千兆字节的数据帧),因此这不是一种选择。我怎么能达到预期的效果?

i.e. I forward fill the rows. However, now I have a dataframe with -1 instead of np.nan. Pandas has the replace function that also has the possibility to use method='ffill', but replace() does not take an axis argument, so to obtain the same result as above, I would need to call df.T.replace(-1, method='ffill').T. Since transposing is quite expensive (especially considering I'm working on a dataframe of multiple gigabytes), this is not an option. How could I achieve the desired result?

推荐答案

使用 mask 填充

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

     0    1    2
0  1.0  2.0  3.0
1  4.0  5.0  5.0
2  6.0  6.0  6.0

这篇关于更改 pandas 轴以替换填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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