Amyunimus Amyunimus - 2 months ago 10
R Question

How to fill in rows with repeating data in pandas?

In R, when adding new data of unequal length to a data frame, the values repeat to fill the data frame:

df <- data.frame(first=c(1,2,3,4,5,6))
df$second <- c(1,2,3)


yielding:

first second
1 1 1
2 2 2
3 3 3
4 4 1
5 5 2
6 6 3


However, pandas requires equal index lengths.

How do I "fill in" repeating data in pandas like I can in R?

Answer

Seems there is no elegant way. This is the workaround I just figured out. Basically create a repeating list just bigger than original dataframe, and then left join them.

import pandas
df = pandas.DataFrame(range(100), columns=['first'])
repeat_arr = [1, 2, 3]
df = df.join(pandas.DataFrame(repeat_arr * (len(df)/len(repeat_arr)+1),
    columns=['second']))