How to reverse a DataFrame in Python Polars

Polars, a DataFrame library entirely coded in Rust, offers Python developers a scalable and efficient data handling framework as an alternative to pandas. It boasts extensive features for streamlined data manipulation and analysis tasks.

Importing the library

We use the following code to import the polars library:

import polars as pl

The reverse function

We can use the DataFrame.reverse function to revert a given DataFrame. This functionality helps to attain the reversal form of the provided DataFrame.

Syntax

Here’s the syntax of the reverse() function:

DataFrame.reverse()

Return value

The function returns a reverted DataFrame, which can be stored and utilized for further implementations.

Coding example

Let’s look at a coding example of the DataFrame.reverse function.

Note: Click the “Run” button to test the code.

import polars as pl
df = pl.DataFrame(
{
"key": [["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]],
"val": [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
}
)
print("- Original DataFrame\n", df)
print("- Reversed DataFrame\n", df.reverse())

Code explanation

Let’s learn about the implementation line by line:

  • Line 1: We import the polars library and give it the pl alias to make it easier to refer to in the code.

  • Line 3: We create the DataFrame named df.

  • Line 4–12: We initialize the DataFrame with two columns: "key" and "val". The "key" column contains the lists of strings, and the "val" column contains the lists of integers.

  • Line 13: We display the original DataFrame.

  • Line 14: We call the reverse() method on the DataFrame df and print the result. The reverse() method reverses the order of the rows in the DataFrame. It does not modify the original DataFrame but returns a new DataFrame with the rows reversed.

Unlock your potential: Polars in Python series, all in one place!

To continue your exploration of Polars, check out our series of Answers below:

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved