mercredi 23 juin 2021

Index of row number minus row index of last non-zero element in dataframe

Using Python, I am trying to compute the interval between non-zero values in a dataframe, and input the interval as an integer in a dataframe. The following is a sample dataset:

Week X Y Z
One 0 3 4
Two 1 1 2
Three 2 0 0
Four 0 0 3
Five 4 1 0

The following are the conditions for the output:

  1. If value == 0, return 0
  2. If value != 0, row number of value minus the last non-zero element

The desired output is this:

Week X Y Z
One 0 0 0
Two 0 1 1
Three 1 0 0
Four 0 0 2
Five 2 3 0

I have tried using for loop and if else, but have always met with some form of error as my python proficiency level isn't high. Hope for some guidance here. Thanks!

Aucun commentaire:

Enregistrer un commentaire