I have a list sub = ["A","B","C","D","E","F"]
and a dataframe of the following format:
I need to write a code for my dataframe to finally look like the following format:
Advertisement
Answer
You can create a cycle using itertools.cycle
, and cut it to the appropriate length using itertools.islice
.
JavaScript
x
8
1
>>> from itertools import cycle, islice
2
3
cycle_list = ["A", "B", "C", "D", "E", "F"]
4
5
list(islice(cycle(cycle_list), 13))
6
7
['A', 'B', 'C', 'D', 'E', 'F', 'A', 'B', 'C', 'D', 'E', 'F', 'A']
8
So, in your case, you can just cut it to the length of the dataframe and assign it as a new column:
JavaScript
1
12
12
1
import pandas as pd
2
import numpy as np
3
4
df = pd.DataFrame(
5
{
6
"col1": np.random.randint(0, 10, size=(13,)),
7
"col2": np.random.randint(100, 1000, size=(13,)),
8
}
9
)
10
11
df["col3"] = list(islice(cycle(cycle_list), len(df)))
12
which gives:
JavaScript
1
15
15
1
col1 col2 col3
2
0 8 413 A
3
1 1 590 B
4
2 8 508 C
5
3 3 147 D
6
4 1 821 E
7
5 5 757 F
8
6 2 857 A
9
7 5 644 B
10
8 4 536 C
11
9 9 959 D
12
10 0 769 E
13
11 0 943 F
14
12 7 276 A
15