Search code examples
pythonpandas

Is it possible to insert a row at an arbitrary position in a dataframe using pandas?


I have a DataFrame object similar to this one:

       onset    length
1      2.215    1.3
2     23.107    1.3
3     41.815    1.3
4     61.606    1.3
...

What I would like to do is insert a row at a position specified by some index value and update the following indices accordingly. E.g.:

       onset    length
1      2.215    1.3
2     23.107    1.3
3     30.000    1.3  # new row
4     41.815    1.3
5     61.606    1.3
...

What would be the best way to do this?


Solution

  • You could slice and use concat to get what you want.

    from pandas import DataFrame, concat
    line = DataFrame({"onset": 30.0, "length": 1.3}, index=[3])
    df2 = concat([df.iloc[:2], line, df.iloc[2:]]).reset_index(drop=True)
    

    This will produce the dataframe in your example output. As far as I'm aware, concat is the best method to achieve an insert type operation in pandas, but admittedly I'm by no means a pandas expert.