Search code examples
pythonpandascounter

Create a pandas column counter that successively counts 4 lines and 6 lines


I have a pandas dataframe with multiple columns and I want to create a counter that successively counts 4 rows and 6 rows. I would like it to look like the dataframe below:

index counter
0 1
1 1
2 1
3 1
4 2
5 2
6 2
7 2
8 2
9 2
10 3
11 3
12 3
13 3

As you can see, the first 4 values in counter column is 1, then next 6 values are 2, then again next 4 values are 3.


Solution

  • Your question is a bit clear after edit, you can create an empty list and a counter variable, then iterate on the range of number of rows incrementing it by 10 i.e. (4+6), then at each iteration, create the required lists of length 4 and 6 with counter and counter+1, add it to the resulting list. Finally take the slice from result list first df.shape[0] values (because it may have few more values than df.shape[0]), and assign it to the new column df['counter'].

    result = []
    counter = 1
    for i in range(0, df.shape[0], 10):
        result += [counter]*4
        counter += 1
        result += [counter]*6
        counter += 1
    
    df['counter'] = result[:df.shape[0]]
        
    # result [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4]
    

    OUTPUT:

        index  counter
    0       0        1
    1       1        1
    2       2        1
    3       3        1
    4       4        2
    5       5        2
    6       6        2
    7       7        2
    8       8        2
    9       9        2
    10     10        3
    11     11        3
    12     12        3
    13     13        3