Reputation: 609
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
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