Inserting a row in Pandas DataFrame is a very straight forward process and we have already discussed approaches in how insert rows at the start of the Dataframe. Now, let’s discuss the ways in which we can insert a row at any position in the dataframe having integer based index.
Solution #1 : There does not exist any in-built function in pandas which will help us to insert a row at any specific position in the given dataframe. So, we are going to write our own customized function to achieve the result.
Note : Inserting rows in-between the rows in Pandas Dataframe is an inefficient operation and the user should avoid it.
Now we will write a customized function to insert a row at any given position in the dataframe.
In case the given row_number is invalid, say total number of rows in dataframe are 100 then maximum value of row_number can be 101, i.e. adding row at the last of dataframe. Any number greater than 101 will given an error message.
Example #2: Another customized function which will use
Pandas.concat() function to insert a row at any given position in the dataframe.
A customized function to insert a row at any given position in the dataframe.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.