pandas replace zeros with previous non zero value

后端 未结 2 519
Happy的楠姐
Happy的楠姐 2020-12-01 14:01

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\         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 14:44

    This is a better answer to the previous one, since the previous answer returns a dataframe which hides all zero values.

    Instead, if you use the following line of code -

    df['A'].mask(df['A'] == 0).ffill(downcast='infer')
    

    Then this resolves the problem. It replaces all 0 values with previous values.

提交回复
热议问题