Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 544
Troas Avatar asked Apr 08 '13 20:04

Troas


People also ask

How do I add a row to a specific position in pandas?

concat() function to insert a row at any given position in the dataframe.

How do I add a row number to a DataFrame in pandas?

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()

How do you add a row to a DataFrame?

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.


1 Answers

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.

like image 139
bdiamante Avatar answered Sep 22 '22 02:09

bdiamante