问题描述
有没有办法对不是 NaN
的值使用 ffill
方法?
Is there a way to use ffill
method on values that are not NaN
?
我的数据框中有 NaN
,但我使用
I have NaN
in my dataframe, but I have added these NaN
using
addNan = sample['colA'].replace(['A'], 'NaN')
这就是我的 DataFrame,df
的样子
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
我正在尝试使用 ffill
填充这些 NaN
,因此它们由最后一个已知值填充.
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)
这没什么区别,也试过 Na
而不是 NaN
This doesn't make a difference, also tried Na
instead of NaN
推荐答案
我认为你需要先将 NaN
替换为 np.nan
,因为 NaN代码>只是文本:
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
如果使用inplace = True
,则返回None
,但就地填充值:
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
这篇关于Pandas - 对 Na 以外的值使用“填充"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!