How to repeat Pandas data frame?

lsheng picture lsheng · May 27, 2014 · Viewed 55.1k times · Source

This is my data frame that should be repeated for 5 times:

>>> x = pd.DataFrame({'a':1,'b':2},index = range(1))
>>> x
   a  b
0  1  2

I wanna have the result like this:

>>> x.append(x).append(x).append(x)
   a  b
0  1  2
0  1  2
0  1  2
0  1  2

But there must be a way smarter than keep appending.. Actually the data frame Im working on should be repeated for 50 times..

I haven't found anything practical, including those like np.repeat ---- it just doesnt work on data frame.

Could anyone help?

Answer

joris picture joris · May 27, 2014

You can use the concat function:

In [13]: pd.concat([x]*5)
Out[13]: 
   a  b
0  1  2
0  1  2
0  1  2
0  1  2
0  1  2

If you only want to repeat the values and not the index, you can do:

In [14]: pd.concat([x]*5, ignore_index=True)
Out[14]: 
   a  b
0  1  2
1  1  2
2  1  2
3  1  2
4  1  2