mercredi 11 décembre 2019

If statement using Numpy.Where and Pandas.Shift in Python

I have a DataFrame similar to below. I am trying to calculate a rolling count of how many times it switches from False to True.

Time   True/False
 1         0
 2         1
 3         1
 4         0
 5         0
 6         0
 7         1
 8         1
 9         0
 10        1
 11        0

The code below is what I have come up with using ```numpy.where, but I am not getting the results I want.

Test['RollingCount'] = np.where(Test['True/False'] == 0, Test['RollingCount'].shift(1),
                       np.where((Test['True/False'] == 1) & (Test['True/False'].shift(1) == 1), Test['RollingCount'].shift(1),
                       np.where((Test['True/False'] == 1) & (Test['True/False'].shift(1) == 0), (Test['RollingCount'].shift(1) + 1),
                       np.where(Test['True/False'] == 1, 1, 0))))

Below is the output I am trying to accomplish. Any idea what I am doing wrong? Is there a better way to approach this?

Time   True/False   RollingCount
 1         0              0
 2         1              1
 3         1              1
 4         0              1
 5         0              1
 6         0              1
 7         1              2
 8         1              2
 9         0              2
 10        1              3
 11        0              3

Aucun commentaire:

Enregistrer un commentaire