Loop over data in a List & assign them in a new column of a dataframe, in round robin method until the length of the dataframe

Question:

I have the below List called List_A

[A,B,C,D,E,F,G]

This has to be looped over a new column (say, col_new) in a dataframe df.

The Assignment needs to be in round robin manner, and of course, it should stop once the length of the Dataframe is reached.

I tried the groupby.cumcount() but was unable to set the limit for the number of iterations over which List values should be assigned.

df['col_new'] = (
    List_A.repeat(df['Col_1'] / len(List_A)).sort_values(
        key=lambda d: d.groupby(s).cumcount(),
        kind='stable',
        ignore_index=True,
    )
)
Asked By: user20710799

||

Answers:

You can try:

from itertools import cycle

list_a = ['A','B','C','D','E','F','G']
df['col_new'] = df.apply(lambda _, c=cycle(list_a): next(c), axis=1)

print(df)

Prints:

   col1 col_new
0     1       A
1     2       B
2     3       C
3     4       D
4     5       E
5     6       F
6     7       G
7     8       A
8     9       B
9    10       C
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.