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

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

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.


I find it more readable to sort rather than slice and concatenate.

line = DataFrame({"onset": 30.0, "length": 1.3}, index=[2.5])
df = df.append(line, ignore_index=False)
df = df.sort_index().reset_index(drop=True)

I think it's even easier without concat or append:

df.loc[2.5] = 30.0, 1.3
df = df.sort_index().reset_index(drop=True)

(Supposing that the index is as provided, starting from 1)

Tags:

Python

Pandas