rxtechsbay
rxtechsbay

Reputation: 45

Adding a column to a data frame with a repeating sequence

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?

Upvotes: 1

Views: 983

Answers (2)

piRSquared
piRSquared

Reputation: 294258

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

Setup

df = pd.DataFrame(dict(old_column=[*'ABCDEFGHIJK']))

Upvotes: 2

rafaelc
rafaelc

Reputation: 59274

Use np.tile

N = 2
np.tile([1,2,3,4,5], N)

where N is the number of repetitions

Upvotes: 3

Related Questions