前向填充nan和零

问题描述 投票:0回答:2

假设我有一个数据框 df1,它有零和 nan:

dates = pd.date_range('20170101',periods=20)
df1 = pd.DataFrame(np.random.randint(10,size=(20,3)),index=dates,columns=['foo','bar','see'])
df1.iloc[3:12,0] = np.nan
df1.iloc[6:17,1] = 0

转发填充 zeors 和 nan 的简洁方法是什么?我尝试了以下方法:

df1 = (df1.fillna(method='ffill', inplace=True)).replace(to_replace=0, method='ffill')

AttributeError: 'NoneType' object has no attribute 'replace'
python pandas fill missing-data
2个回答
6
投票

让我们使用

replace
将零替换为
nan
,然后用
ffill
:

df1.replace(0, np.nan).ffill()

输出:

            foo  bar  see
2017-01-01  2.0  1.0    4
2017-01-02  2.0  2.0    6
2017-01-03  2.0  8.0    3
2017-01-04  2.0  6.0    1
2017-01-05  2.0  8.0    4
2017-01-06  2.0  9.0    6
2017-01-07  2.0  9.0    8
2017-01-08  2.0  9.0    5
2017-01-09  2.0  9.0    8
2017-01-10  2.0  9.0    7
2017-01-11  2.0  9.0    3
2017-01-12  2.0  9.0    6
2017-01-13  5.0  9.0    4
2017-01-14  6.0  9.0    9
2017-01-15  7.0  9.0    4
2017-01-16  6.0  9.0    2
2017-01-17  2.0  9.0    5
2017-01-18  3.0  1.0    1
2017-01-19  3.0  8.0    1
2017-01-20  2.0  5.0    7

2
投票

我认为@ScottBoston 的回答是最地道的。
然而,另一种方法是使用

pd.DataFrame.mask

df1.mask(df1 == 0).ffill()
© www.soinside.com 2019 - 2024. All rights reserved.