astroboy
astroboy

Reputation: 197

replicate entire dataframe 'x' times in Python

I've a sample dataframe

     city
  0  Los Angles
  1  New York
  2  Texas
  3  Washington DC

How can I replicate the above dataframe without changing the order?

Expected outcome:

     city
  0  Los Angles
  1  New York
  2  Texas
  3  Washington DC
  4  Los Angles
  5  New York
  6  Texas
  7  Washington DC
  8  Los Angles
  9  New York
  10 Texas
  11 Washington DC

Upvotes: 0

Views: 36

Answers (2)

IoaTzimas
IoaTzimas

Reputation: 10624

You can use pd.concat:

result=pd.concat([df]*x).reset_index(drop=True)

print(result)

Output (for x=3):

       city
  0  Los Angles
  1  New York
  2  Texas
  3  Washington DC
  4  Los Angles
  5  New York
  6  Texas
  7  Washington DC
  8  Los Angles
  9  New York
  10 Texas
  11 Washington DC

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150745

How about:

pd.concat([df]*3, ignore_index=True)

Output:

             city
0      Los Angles
1        New York
2           Texas
3   Washington DC
4      Los Angles
5        New York
6           Texas
7   Washington DC
8      Los Angles
9        New York
10          Texas
11  Washington DC

Upvotes: 2

Related Questions