Skip to content
Advertisement

How do I append a repeating list to a dataframe?

I have a list sub = ["A","B","C","D","E","F"] and a dataframe of the following format:

enter image description here

I need to write a code for my dataframe to finally look like the following format:

enter image description here

Advertisement

Answer

You can create a cycle using itertools.cycle, and cut it to the appropriate length using itertools.islice.

>>> from itertools import cycle, islice
...
... cycle_list = ["A", "B", "C", "D", "E", "F"]
...
... list(islice(cycle(cycle_list), 13))

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

So, in your case, you can just cut it to the length of the dataframe and assign it as a new column:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "col1": np.random.randint(0, 10, size=(13,)),
        "col2": np.random.randint(100, 1000, size=(13,)),
    }
)

df["col3"] = list(islice(cycle(cycle_list), len(df)))

which gives:

    col1  col2 col3
0      8   413    A
1      1   590    B
2      8   508    C
3      3   147    D
4      1   821    E
5      5   757    F
6      2   857    A
7      5   644    B
8      4   536    C
9      9   959    D
10     0   769    E
11     0   943    F
12     7   276    A
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement