How to perform the transpose of a Python Polars DataFrame

Polars is a powerful library for fast and efficient data manipulation. It’s designed to provide high-performance operations on large datasets and handles them more quickly than the pandas library.

Note: Learn more about the difference between the Polars and pandas library here.

The DataFrame.transpose() function

The DataFrame.transpose() function in polars facilitates performing transpose of the DataFrame by interchanging the rows with columns and vice versa.

The transpose of the DataFrame
The transpose of the DataFrame

Syntax

The syntax for the transpose function is given by:

DataFrame.transpose(<include_header>, <header_name>, <column_names>)
  • include_header: It’s a boolean parameter that will add the column names as the first column in the transposed DataFrame if its value is set to True. It’s an optional parameter.

  • header_name: It’s also an optional parameter that is used to specify the name for the column added when the include_header parameter is set.

  • column_names: It’s another optional parameter to add the column names for the transposed DataFrame.

Return value

The function returns a DataFrame that contains the transpose of the given DataFrame.

Code

import polars as pl
df = pl.DataFrame(
{
"Product": ["Note holder", "Scissors", "Stapler", "Paper clip"],
"Price": [2, 1, 24, 25],
"Quantity": [70, None, 30, 200],
}
)
# Computing the transpose
print(df.transpose())
# Computing the transpose with the header included as a new column
print(df.transpose(include_header=True))
# Computing the transpose with the header included and the column name specified for it
print(df.transpose(include_header=True, header_name="Category"))
# Computing the transpose with column names
print(df.transpose(column_names=["Item 1", "Item 2", "Item 3", "Item 4"]))

Explanation

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

  • Lines 2–8: We define our DataFrame as df for the stationary shop with the product’s name, price, and quantity columns.

  • Line 10: We compute and print the transpose of the DataFrame using the df.transpose() function.

  • Line 12: We compute and print the transpose of the DataFrame using the df.transpose() function with the include_header set to True to include the header as a new column.

  • Line 14: We compute and print the transpose with the header_name set to Category for adding a column name for the header included as a column.

  • Line 16: We compute and print the transpose with the column_names set to Item 1, Item 2, Item 3, and Item 4.

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