-1

How do I make a list or column in pandas which number in this column increase itself by step of 1 and when it hits an certain number (let's say 5) it return to 1 and repeat this process? My scripts like below and it won't work as expected:

i = 0
lista = []
for i in range(50):
        i += 1
        if i == 5:
            continue
        lista.append(i)

print(i)
# what I wanted from this code is like :
1
2
3
4
5
.
.
.
# repeat printing 1-5 for 10 times
Tian Chu
  • 35
  • 4

2 Answers2

2

First using loops in pandas is antipattern, mainly if exist vectorized solutions, here numpy.tile:

df = pd.DataFrame({'col': np.tile(np.arange(1, 6), 10)})
print (df.head(12))
    col
0     1
1     2
2     3
3     4
4     5
5     1
6     2
7     3
8     4
9     5
10    1
11    2
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

In the simplest way that occurs to me:

lista = []
for i in range(50):
    lista.append(i%5+1)
print(lista)

This could also be written as a list comprehension, which is only one line of code and way cooler ;)

lista = [ i%5+1 for i in range(50) ]
AllAboutMike
  • 121
  • 7