Home > front end >  How to create a new column through a specific condition?
How to create a new column through a specific condition?

Time:11-10

I have a column like this:

1
0
0
0
0
1
0
0
0
1
0
0

and need as result:

1
1
1
1
1
2
2
2
2
3
3
3

A method/algorithm that divides into ranks from 1 to 1 and gives them successively values.
Any idea?

CodePudding user response:

You can loop through the list and use a counter to update the column value, and increment it everytime you find the number 1.

def rank(lst):
    counter = 0
    for i, column in enumerate(lst):
        if column == 1:
            counter =1
        lst[i] = counter

CodePudding user response:

def fill_arr(arr): 
    curr = 1 
    for i in range(1, len(arr)): 
        arr[i] = curr  
        if i < len(arr)-1 and arr[i 1] == 1: 
            curr  = 1 
    return arr

A quick test

arr = [1,0,0,0,1,0,0,0,1,0,0]                                                                                 
fill_arr(arr)                                                                                                 
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]

The idea is as follows:

  1. keep track of the number of 1s we encounter it curr by looking ahead and increment it as we see new 1s.
  2. set the elements at the current index to curr.
  3. we start at index 1 since we know that there is a one at index zero. This helps us reduce edge cases and make the algorithm easier to manage.
  • Related