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.
CodePudding user response:
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
CodePudding user response:
from math import ceil
df['new_column'] = (x*(ceil(len(df)/len(x))))[:len(df)]