How to replace value in sequences of a boolean list?

Viewed 147

I have a list like this:

list_1 = [True, False, True, False, True, True, True, False, False, False, True, True, False]

In this list, there are sequences that start with a False and end with a True. I need help to implement replacing values of this list in this way:

  • Replace False values of these sequences with a -2^k series. The True value after the last False of each sequence is +2^k, with k as the position of the value in a sequence.
  • Other True values that don't belong to any of those sequences will retain value 1.

The output looks like this:

list_2 = [1, -1, 2, -1, 2, 1, 1, -1, -2, -4, 8, 1, -1]
1 Answers

Since you tagged pandas:

# turn data into series
s = pd.Series(list_1)

# mark the blocks ending with True
blocks = s.shift(fill_value=0).cumsum()

# compute the positions within blocks and raise to power 2
powers = 2**s.groupby(blocks).cumcount()

#output:
np.where(s, 1,-1)*powers.values

Output:

array([ 1, -1,  2, -1,  2,  1,  1, -1, -2, -4,  8,  1, -1])
Related