Polars - Get the Number of Rows, Columns, and Elements (Size) of a DataFrame

Get the Number of Rows

To find the number of rows in a DataFrame, use the height attribute:

import polars as pl

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22]}
df = pl.DataFrame(data)

# Get the number of rows
num_rows = df.height
print(f"Number of rows: {num_rows}")

Get the Number of Columns

To get the number of columns, use the width attribute:

num_columns = df.width
print(f"Number of columns: {num_columns}")

Get the Total Number of Elements (Size)

The total number of elements in the DataFrame (i.e., the product of rows and columns) can be calculated as follows:

num_elements = num_rows * num_columns
print(f"Total number of elements (size): {num_elements}")

Now you know how to quickly retrieve the size information for your Polars DataFrame. Whether youโ€™re analyzing data or building machine learning models, understanding the dimensions of your DataFrame is essential.

Happy coding with Polars! ๐Ÿš€๐Ÿ“Š


Publish Date: 2024-05-08, Update Date: 2024-05-08