Luca91
Luca91

Reputation: 609

Pandas: how to create a simple counter that increases each n rows?

Is there a way to create a Counter that increases by one each n rows?

example ===> Counter increasing each 4 rows:

        counter
    0    1
    1    1
    2    1
    3    1
    4    2
    5    2
    6    2
    7    2
    8    3
    9    3

I was trying df['counter'] = np.arange(len(df)//4) but I get lenght of index error

thanks

Upvotes: 3

Views: 371

Answers (1)

jezrael
jezrael

Reputation: 863541

You are close, need:

df['counter'] = np.arange(len(df)) // 4 + 1
print (df)
   counter
0        1
1        1
2        1
3        1
4        2
5        2
6        2
7        2
8        3
9        3

Your solution not working, because array with 2 values was assigned to column:

print (len(df)//4)
2

print (np.arange(len(df)//4))
[0 1]

But if need array with same size like DataFrame:

print (np.arange(len(df)))
[0 1 2 3 4 5 6 7 8 9]

Upvotes: 3

Related Questions