How to drop a column using Polars

Polars is a Python library designed specifically for working with tabular data structures represented as DataFrames. The tabular data structure is similar to the table, which means that it consists of rows and columns.

In this Answer, we'll use the drop method to remove or drop a column from the DataFrame in Polars.

Syntax

We'll use the following syntax of the drop method to remove a column from the DataFrame:

DataFrame.drop(column_name: str, *more_columns: str)
Syntax of drop() method

Parameters

  • column: This specifies the name of the column that we want to remove from the DataFrame.

  • *more_columns: This specifies the additional name of the columns that we want to remove from the DataFrame. Thus, we can drop more than one column at a time from the DataFrame in Polars.

Code example

Here is the coding example of the drop method to drop a column from the DataFrame:

import polars as pl
df = pl.DataFrame({
"Name": ["John", "Harry", "Peter"],
"Roll #": [1, 2, 3],
"Address": ["abc", "lmn", "xyz"]
})
df = df.drop("Roll #") # or use df.drop([col1, col2, .., colN]) to drop N columns
print(df)

Code explanation

Line 1: We import the Polars library named pl.

Lines 3–7: We specify that the DataFrame consists of 3 rows and 3 columns.

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

Line 10: We print the resulting DataFrame after removing the Roll # column.

Test yourself

Take a quiz to test your understanding.

1

How do you drop a column in Polars?

A)

df.drop_column(column_name)

B)

df.remove_column(column_name)

C)

df.delete_column(column_name)

D)

df.drop(column_name)

Question 1 of 20 attempted
Copyright ©2024 Educative, Inc. All rights reserved