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.
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)
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.
Here is the coding example of the drop
method to drop a column from the DataFrame:
import polars as pldf = 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 columnsprint(df)
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.
Take a quiz to test your understanding.
How do you drop a column in Polars?
df.drop_column(column_name)
df.remove_column(column_name)
df.delete_column(column_name)
df.drop(column_name)