What is DataFrame.sort in Polars?

Polars is a Python library that makes working with tables of data (using DataFrames) easier and faster. It's designed to handle large amounts of data and allows you to perform various data tasks easily. If you need to work with data tables in Python, Polars is a great tool to consider.

In this Answer, we’ll use the DataFrame.sort method to sort the DataFrame based on the values in one or more columns.

Syntax

We’ll use the following syntax of the DataFrame.sort method to remove a column from the DataFrame:

DataFrame.sort(by, reverse=False, in_place=False)

Parameters

  • by: A single column name or a list of column names based on which the DataFrame should be sorted.

  • reverse: It is a boolean value which indicates how to sort the DataFrame whether it is in descending order (True) or ascending order (False). The default is False (ascending order).

  • in_place: It is a boolean value that decides if the DataFrame should be sorted directly in place (True) or if a new sorted DataFrame should be created (False). The default option is False.

Code example

Here is the coding example of the DataFrame.sort() method to sort the DataFrame in Polars:

import polars as pl
data = {
"Name": ["John", "Harry", "Peter"],
"Roll #": [3, 1, 2],
"Address": ["abc", "lmn", "xyz"]
}
df = pl.DataFrame(data)
sorted_df = df.sort("Roll #")
print(sorted_df)

Explanation

  • Line 1: We import the Polars library as pl.

  • Lines 26: We create a data table with three rows and three columns.

  • Line 8: We add this table in the DataFrame named df.

  • Line 9: We sort the Roll # column from the DataFrame using the sort method.

  • Line 10: We display the resulting DataFrame after sorting (i.e., sorted_df).

Test yourself

Take a quiz to test your understanding.

1

What is DataFrame.sort in Polars used for?

A)

Creating a new data DataFrame frame from scratch

B)

Filtering rows based on a condition

C)

Sorting rows in a DataFrame based on specified columns

D)

Grouping rows based on a specific column

Question 1 of 50 attempted

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved