Skip to content
Advertisement

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.

Advertisement

Answer

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’].

JavaScript

OUTPUT:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement