Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

python - pandas replace zeros with previous non zero value

I have the following dataframe:

index = range(14)
data = [1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2, 1]
df = pd.DataFrame(data=data, index=index, columns = ['A'])

How can I fill the zeros with the previous non-zero value using pandas? Is there a fillna that is not just for "NaN"?.

The output should look like:

[1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1]

(This question was asked before here Fill zero values of 1d numpy array with last non-zero values but he was asking exclusively for a numpy solution)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use replace with method='ffill'

In [87]: df['A'].replace(to_replace=0, method='ffill')
Out[87]:
0     1
1     1
2     1
3     2
4     2
5     4
6     6
7     8
8     8
9     8
10    8
11    8
12    2
13    1
Name: A, dtype: int64

To get numpy array, work on values

In [88]: df['A'].replace(to_replace=0, method='ffill').values
Out[88]: array([1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1], dtype=int64)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...