Home > Back-end >  Duplicate a single row at index?
Duplicate a single row at index?

Time:11-11

In the past hour I was searching here and couldn't find a very simple thing I need to do, duplicate a single row at index x, and just put in on index x 1.

df

  a  b
0 3  8
1 2  4
2 9  0
3 5  1

copy index 2 and insert it as is in the next row:

  a  b
0 3  8
1 2  4
2 9  0
3 9  0 # new row
4 5  1

What I tried is concat(with my own columns names) which make a mess.

line = pd.DataFrame({"date": date, "event": None}, index=[index 1])
return pd.concat([df.iloc[:index], line, df.iloc[index:]]).reset_index(drop=True)

How to simply duplicate a full row at a given index ?

CodePudding user response:

Got it.

df.loc[index 0.5] =  df.loc[index].values
return df.sort_index().reset_index(drop = True)

CodePudding user response:

You can use repeat(). Fill in the dictionary with the index and the key, and how many extra rows you would like to add as the value. This can work for multiple values.

d = {2:1}
df.loc[df.index.repeat(df.index.map(d).fillna(0) 1)].reset_index()

Output:

   index  a  b
0      0  3  8
1      1  2  4
2      2  9  0
3      2  9  0
4      3  5  1
  • Related