Search code examples
python-3.xpandasdataframeseries

How can I duplicate a row and append it directly after the duplicated row using pandas?


I've been trying to figure this problem for a couple of hours now and seem to reach a dead end everytime. A small example of what I want to do is shown below.

Normal Series
a
b
c
d
Duplicated Series
a
a
b
b
c
c
d
d

Solution

  • Try with loc and df.index.repeat:

    >>> df.loc[df.index.repeat(2)]
      Normal Series
    0             a
    0             a
    1             b
    1             b
    2             c
    2             c
    3             d
    3             d
    >>> 
    

    Or with reset_index:

    >>> df.loc[df.index.repeat(2)].reset_index(drop=True)
      Normal Series
    0             a
    1             a
    2             b
    3             b
    4             c
    5             c
    6             d
    7             d
    >>>