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.
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)
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
.
Here is the coding example of the DataFrame.sort()
method to sort the DataFrame in Polars:
import polars as pldata = {"Name": ["John", "Harry", "Peter"],"Roll #": [3, 1, 2],"Address": ["abc", "lmn", "xyz"]}df = pl.DataFrame(data)sorted_df = df.sort("Roll #")print(sorted_df)
Line 1: We import the Polars library as pl
.
Lines 2–6: 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
).
Take a quiz to test your understanding.
What is DataFrame.sort
in Polars used for?
Creating a new data DataFrame frame from scratch
Filtering rows based on a condition
Sorting rows in a DataFrame based on specified columns
Grouping rows based on a specific column
Free Resources