0

I have a function that assigns a counter to each row, starting from one if the row is changed from True to False or False to True. I would like to vectorize this or at least to have a better performance then the apply function.

Any suggestion?

def boolean_counter(self, df, target, source):
        self.sourcefield    = source
        df[target] = df.apply(self.__counter, axis=1)
        return df

def __counter(self, row):
        """
        Assign counter from switch
        """
        if row[self.sourcefield]:
            self.currentcounter_false = 0
            self.currentcounter_true = self.currentcounter_true + 1
            return self.currentcounter_true
        else:
            self.currentcounter_true = 0
            self.currentcounter_false = self.currentcounter_false  + 1
            return self.currentcounter_false

The output should be like:

TRUE    1
TRUE    2
TRUE    3
TRUE    4
TRUE    5
FALSE   1
FALSE   2
TRUE    1
FALSE   1
FALSE   2
TRUE    1
TRUE    2
FALSE   1
TRUE    1
TRUE    2
TRUE    3
TRUE    4
TRUE    5
TRUE    6
Youri
  • 1
  • 1

0 Answers0