Pandas - Using 'ffill' on values other than Na

我的梦境 提交于 2021-01-27 16:42:41

问题


Is there a way to use ffill method on values that are not NaN?

I have NaN in my dataframe, but I have added these NaN using

addNan = sample['colA'].replace(['A'], 'NaN')

So this is what my DataFrame, df looks like

ColA  ColB  ColC  ColD
 B      A     A    C
 NaN    B     A    A
 C      D     D    A
 NaN    A     A    B

And I'm trying to fill these NaN using ffill , so they are populated by the last known value.

fill = df.fillna(method='ffill', inplace = True)

This doesn't make a difference, also tried Na instead of NaN


回答1:


I think you need first replace NaN to np.nan, because NaN is only text:

import pandas as pd
import numpy as np

print (sample)
  ColA ColB ColC ColD
0    B    A    A    C
1    A    B    A    A
2    C    D    D    A
3    A    A    A    B

sample['ColA'] = sample['ColA'].replace(['A'], np.nan)
print (sample)
  ColA ColB ColC ColD
0    B    A    A    C
1  NaN    B    A    A
2    C    D    D    A
3  NaN    A    A    B

If use inplace = True, it return None, but inplace fill values:

sample.fillna(method='ffill', inplace = True)
#sample.ffill(inplace = True)
print (sample)
  ColA ColB ColC ColD
0    B    A    A    C
1    B    B    A    A
2    C    D    D    A
3    C    A    A    B


来源:https://stackoverflow.com/questions/38915330/pandas-using-ffill-on-values-other-than-na

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!