Home > Back-end >  Duplicate a selected row and put the duplicate just below in a Pandas DataFrame
Duplicate a selected row and put the duplicate just below in a Pandas DataFrame

Time:12-25

I have a Pandas dataframe like this :

id  A   B
0   2   2
1   1   1
2   3   3
3   7   7

And I want to duplicate the first row 3 times just below the selected row :

id  A   B
0   2   2
1   2   2
2   2   2
3   2   2
4   1   1
5   3   3
6   7   7

Is there a method that already exist in Pandas library ?

CodePudding user response:

Use reindex and Index.repeat to create your dataframe:

>>> df.reindex(df.index.repeat([3]   [1] * (len(df) - 1)))
   id  A  B
0   0  2  2
0   0  2  2
0   0  2  2
1   1  1  1
2   2  3  3
3   3  7  7

Another way:

>>> df.loc[[df.index[0]]*3   df.index[1:].tolist()]
   id  A  B
0   0  2  2
0   0  2  2
0   0  2  2
1   1  1  1
2   2  3  3
3   3  7  7

A more generalized way proposed by @MuhammadHassan:

row_index = 0
repeat_time = 3

>>> df.reindex(df.index.tolist()   [row_index]*repeat_time).sort_index()
   id  A  B
0   0  2  2
0   0  2  2
0   0  2  2
0   0  2  2
1   1  1  1
2   2  3  3
3   3  7  7

CodePudding user response:

There is no built-in method for doing just this. However, you can create a list of indexes, and use df.loc df.index.repeat:

new_df = df.loc[df.index.repeat([4]   [1] * (len(df) - 1))].reset_index(drop=True)

Output:

>>> new_df
   id  A  B
0   0  2  2
1   0  2  2
2   0  2  2
3   0  2  2
4   1  1  1
5   2  3  3
6   3  7  7

CodePudding user response:

Let us try

n=3
row = 0 
df = df.append(df.loc[[row]*(n-1)]).sort_index()
df
   id  A  B
0   0  2  2
0   0  2  2
0   0  2  2
1   1  1  1
2   2  3  3
3   3  7  7
  • Related