What is the DataFrame.clear() function in Polars Python?

Polars, a Rust-based library, outperforms pandas for large data manipulation, especially with tabular data. It offers a high-speed DataFrame for efficient slicing, filtering, and transformations in Python and Rust.

The clear() function

The DataFrame.clear() method generates a copy of the null-filled DataFrame. It accepts a value as a parameter, e.g., nn. If nnis 00, it returns an empty DataFrame and if nn is greater than 00, it creates a new DataFrame with nn rows, filling them with null values. The new DataFrame maintains the same structure as the original one, and it can have more rows than the original DataFrame.

Syntax

Here’s the syntax of the DataFrame.clear() function:

Dataframe.clear(n)

Here n represents the number of rows filled with null values in the cleared frame.

Code example

Let’s have a look at a coding example of clearing the Dataframe using clear() method in polars:

import polars as pl
df = pl.DataFrame(
{
"Country": ["Japan", "Singapore", "Indonesia", "Italy", "France"],
"City": ["Osaka", "Tengah", "Medan", "Rome", "Paris"],
"Salary": [10000, 85676, 367576, 18939, None],
"Role": ["Engineer", "Doctor", None , None, "Chef"],
}
)
# Return an empty Dataframe
print(df.clear())
# Return a Dataframe with 2 rows
print(df.clear(n = 2))
# Return a Dataframe with 7 rows(more than the original Dataframe)
print(df.clear(n = 7))

Explanation

In the above code:

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

  • Lines 3–10: We define our DataFrame as df, which includes CountryCity, Salary, and Role.

  • Lines 13–17: We implement the clear() method to the created Dataframe, passing different arguments, resulting in an empty DataFrame, a DataFrame with 2 rows, and another DataFrame containing more than the defined rows (7) in the original DataFrame.

Conclusion

In conclusion, the DataFrame.clear() function in polars Python generates a null-filled DataFrame copy. It produces an empty DataFrame for nn=0 value and a new DataFrames with nn null-filled rows for non-zero values, maintaining the original structure.

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