问题
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