Skip to content
Advertisement

Function to move specific row to top or bottom of pandas dataframe

I have two functions which shift a row of a pandas dataframe to the top or bottom, respectively. After applying them more then once to a dataframe, they seem to work incorrectly.

These are the 2 functions to move the row to top / bottom:

JavaScript

Note: I don’t want to reset_index for the returned df.

Example:

JavaScript

This is my dataframe:

Now, apply function for the first time. Move row with index 0 to bottom:

JavaScript

The result is exactly what I want.

Now, apply function again. This time move row with index 2 to the bottom:

JavaScript

Well, this is not what I was expecting. There must be a problem when I want to apply the function a second time. The promblem is analog to the function shift_row_to_top.

My question is:

  • What’s going on here?
  • Is there a better way to shift a specific row to top / bottom of the dataframe? Maybe a pandas-function?
  • If not, how would you do it?

Advertisement

Answer

Your problem is these two lines:

JavaScript

idx is a list and idx.pop(index_to_shift) removes the item at index index_to_shift of idx, which is not necessarily valued index_to_shift as in the second case.

Try this function:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement