0

I have list containing numbers x =(1,2,3,4,5,6,7,8) I also have a DataFrame with 1000+ rows. The thing I need is to assign the numbers in the list into a column/creating a new column, so that the rows 1-8 contain the numbers 1-8, but after that it starts again, so row 9 should contain number 1 and so on.

It seems really easy, but somehow I cannot manage to do this.

1

2 Answers 2

1

Here are two possible ways (example here with 3 items to repeat):

with numpy.tile

df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = np.tile(x, len(df)//len(x)+1)[:len(df)]

with itertools

from itertools import cycle, islice

df = pd.DataFrame({'col': range(10)})
x = (1,2,3)
df['newcol'] = list(islice(cycle(x), len(df

input:

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

output:

   col  newcol
0    0       1
1    1       2
2    2       3
3    3       1
4    4       2
5    5       3
6    6       1
7    7       2
8    8       3
9    9       1
Sign up to request clarification or add additional context in comments.

1 Comment

Tanks a lot, it worked ike a charm!
0
from math import ceil
df['new_column'] = (x*(ceil(len(df)/len(x))))[:len(df)] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.