Is there any alternative way to to reverse rows in a DataFrame?

I’m facing an issue while working with a Pandas DataFrame where I need to reverse the order of rows. Although I have used the iloc function for this purpose, I’m uncertain if it is the best approach for reversing rows in a DataFrame. I’m seeking guidance and suggestions on the most efficient way to reverse rows in a Pandas DataFrame. If anyone has any experience or knowledge regarding this, please share your insights with me. Your help would be greatly appreciated.

  • The iloc method is used to select rows and columns in a DataFrame by their integer position.

  • It uses the following syntax: df.iloc[row_indexer, column_indexer].

  • df.iloc[::-1] returns a new DataFrame with the rows in reverse order. The columns are not affected because I did not specify a column indexer.

Yes, @nimrah, there is an alternate way of achieving your task. You can use the loc indexer in the same way as you used the iloc indexer. However, remember that loc is a label indexer and iloc is an integer-based position indexer. The code below shows how you can use this to reverse the rows:

  • The df.loc[::-1] syntax only works when you have a labeled index in your dataframe. If your dataframe has a default integer index, you can use df.iloc[::-1] instead.
  • Using the df.loc[::-1] method to reverse the order of rows in a dataframe can be useful when you need to manipulate dataframes using label-based indexing.