1

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?

1
  • Welcome to StackOverflow. To make your question fit the format of this site, it is necessary, that you include also what you have researched so far, and where exactly you are stuck. See also: stackoverflow.com/help/how-to-ask. The easiest way is to include an MVCE showing how you populate your dataframe and where in the script you are missing bits. Commented Aug 7, 2019 at 20:31

2 Answers 2

3

Use np.tile

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

where N is the number of repetitions

Sign up to request clarification or add additional context in comments.

Comments

2

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']))

2 Comments

This is exactly what I need, but when I try to run this code, I am getting a syntax error - df = pd.DataFrame(dict(old_column=[*'ABCDEFGHIJK'])) ^ SyntaxError: invalid syntax
You're probably using an older version of Python that doesn't allow for my "slick" use of [*...] so use the list callable instead df.assign(new_column=list(islice(cycle(pat), len(df))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.