I am trying to add a column to a data frame and have it pre populated with a repeating sequence.
For example:
new_column
1
2
3
4
5
1
2
3
4
5
.
.
.
Is there a way to achieve this using pandas functions and not having to run a loop?
itertools
, islice
and cycle
This keeps going through the pattern and doesn't matter if the length of the dataframe is a multiple of the length of the pattern.
from itertools import islice, cycle
pat = [1, 2, 3, 4, 5]
df.assign(new_column=[*islice(cycle(pat), len(df))])
old_column new_column
0 A 1
1 B 2
2 C 3
3 D 4
4 E 5
5 F 1
6 G 2
7 H 3
8 I 4
9 J 5
10 K 1
df = pd.DataFrame(dict(old_column=[*'ABCDEFGHIJK']))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.