Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to repeat each row n times in pandas so that it looks like this?

I want to know how to repeat each row n times in pandas in this fashion

I want this below result(With df_repeat = pd.concat([df]*2, ignore_index=False) I can’t get expected result ):

Original Dataset:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index value
0 x
1 x
2 x
3 x
4 x
5 x

Dataframe I want:

index value
0 x
0 x
1 x
1 x
2 x
2 x
3 x
3 x
4 x
4 x
5 x
5 x

>Solution :

You can repeat the index:

df_repeat = df.loc[df.index.repeat(2)]

output:

   index value
0      0     x
0      0     x
1      1     x
1      1     x
2      2     x
2      2     x
3      3     x
3      3     x
4      4     x
4      4     x
5      5     x
5      5     x

For a clean, new index:

df_repeat = df.loc[df.index.repeat(2)].reset_index(drop=True)

output:

    index value
0       0     x
1       0     x
2       1     x
3       1     x
4       2     x
5       2     x
6       3     x
7       3     x
8       4     x
9       4     x
10      5     x
11      5     x

on Series

Should you have a Series as input, there is a Series.repeat method:

# create a Series from the above DataFrame
s = df.set_index('index')['value']

s.repeat(2)

output:

index
0    x
0    x
1    x
1    x
2    x
2    x
3    x
3    x
4    x
4    x
5    x
5    x
Name: value, dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading