I have a datafame:
import pandas as pd df = pd.DataFrame( { "key": ["K0", "K1", "K2", "K3", "K4", "K5", "K6", "K7", "K8", "K9",'K10', 'K11',], "team": ['a', 'd', 'w', 'a', 'c', 's', 'x', 'd', 'a', 'f', 'e', 'r'], } ) df = key team 0 K0 a 1 K1 d 2 K2 w 3 K3 a 4 K4 c 5 K5 s 6 K6 x 7 K7 d 8 K8 a 9 K9 f 10 K10 e 11 K11 r
What is the shortes / simples way to add a repeating counter column like this?:
key team counter 0 K0 a 0 1 K1 d 0 2 K2 w 0 3 K3 a 1 4 K4 c 1 5 K5 s 1 6 K6 x 2 7 K7 d 2 8 K8 a 2 9 K9 f 3 10 K10 e 3 11 K11 r 3
My feeling tells me, that there must be a one-line solution (maybe a bit longer). But all I can think of would be much longer and complex.
How would you approach this?
Advertisement
Answer
try:
df['counter']=df.index//3
OR
If you have a custom index then you can use:
df['counter']=[x//3 for x in range(len(df))]
output of df
:
key team counter 0 K0 a 0 1 K1 d 0 2 K2 w 0 3 K3 a 1 4 K4 c 1 5 K5 s 1 6 K6 x 2 7 K7 d 2 8 K8 a 2 9 K9 f 3 10 K10 e 3 11 K11 r 3