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?
concat() function to insert a row at any given position in the dataframe.
You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement. Other options available to add rows to the dataframe are, append()
You can create a DataFrame and append a new row to this DataFrame from dict, first create a Python Dictionary and use append() function, this method is required to pass ignore_index=True in order to append dict as a row to DataFrame, not using this will get you an error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With