I have a datafame:
JavaScript
x
24
24
1
import pandas as pd
2
3
df = pd.DataFrame(
4
{
5
"key": ["K0", "K1", "K2", "K3", "K4", "K5", "K6", "K7", "K8", "K9",'K10', 'K11',],
6
"team": ['a', 'd', 'w', 'a', 'c', 's', 'x', 'd', 'a', 'f', 'e', 'r'],
7
}
8
)
9
10
df =
11
key team
12
0 K0 a
13
1 K1 d
14
2 K2 w
15
3 K3 a
16
4 K4 c
17
5 K5 s
18
6 K6 x
19
7 K7 d
20
8 K8 a
21
9 K9 f
22
10 K10 e
23
11 K11 r
24
What is the shortes / simples way to add a repeating counter column like this?:
JavaScript
1
14
14
1
key team counter
2
0 K0 a 0
3
1 K1 d 0
4
2 K2 w 0
5
3 K3 a 1
6
4 K4 c 1
7
5 K5 s 1
8
6 K6 x 2
9
7 K7 d 2
10
8 K8 a 2
11
9 K9 f 3
12
10 K10 e 3
13
11 K11 r 3
14
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:
JavaScript
1
2
1
df['counter']=df.index//3
2
OR
If you have a custom index then you can use:
JavaScript
1
2
1
df['counter']=[x//3 for x in range(len(df))]
2
output of df
:
JavaScript
1
14
14
1
key team counter
2
0 K0 a 0
3
1 K1 d 0
4
2 K2 w 0
5
3 K3 a 1
6
4 K4 c 1
7
5 K5 s 1
8
6 K6 x 2
9
7 K7 d 2
10
8 K8 a 2
11
9 K9 f 3
12
10 K10 e 3
13
11 K11 r 3
14