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

Time:07-20

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:

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

CodePudding user response:

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
  • Related