Transposing Columns With Pandas in Python

A quick answer

A pandas DataFrame can be transposed using pandas.DataFrame.transpose() function or NumPy’s transpose() function. For example,

# create pandas DataFrame
import pandas as pd
import numpy as np
df = pd.DataFrame({"Name": ["Smith"], "Adm": [66]})

You can then transpose df using any of the following lines

df.transpose() # you can also use df.T
np.transpose(df)
---

The transpose operator is used to flip a table over its leading diagonal; that is, it swaps the rows and columns of a table.

Figure 1: Transposing operator flipping a table along the leading diagonal. The transposed table now has the columns of the original table being the rows and vice versa.

Transposing pandas DataFrame using the transpose() function

Pandas DataFrame is a tabular data structure that can be transposed using pandas.DataFrame.transpose() function which has the following syntax:

pandas.DataFrame.transpose(*args, copy=False)

Where:

  • *args (optional) is a tuple holding arguments accepted to promote compatibility with NumPy and
  • copy (default: False). We will discuss this in detail in the “View vs Copy” subsection.

The function returns a transposed pandas DataFrame.

Note: The same function can be accessed using the property T. That means pandas.DataFrame.T can also be used to transpose a DataFrame.

Let’s see some examples.

Example 1

In this first example, we create a pandas DataFrame without explicitly defining our indices. By default, pandas will make them for us as 0, 1, 2,…

import pandas as pd
data = {"Name": ["Smith", "Alice"],
    	"Mark": [67, 78]}
print("Original DataFrame:")
df = pd.DataFrame(data)
print(df)
print("Transposed DataFrame:")
df_transposed = df.transpose() #or df.T
print(df_transposed)

Output (formatted for better display):

Example 2

Unline in Example 1, we passed index values here. Like before, we used the transpose() function to transpose the DataFrame.

import pandas as pd
data2  = {"Height_col1": [145.7, 179.8, 152.9],
"BMI_col2": [24.6, 22.8, 25]}
df2 = pd.DataFrame(data2, index=[f"Row{i}" for i in range(1,4)])
df2_transposed = df2.transpose() # or df2.T
print('Original tabe:')
print(df2)
print("After transposing:")
print(df2_transposed)

Output (formatted for better viewing):

Note: pandas.DataFrame.transpose() does not perform the operation in place; therefore, the original table in memory doesn’t change when transposed. If you want to transpose the table in place, you can assign the transposed table the same variable name as the original DataFrame.

View vs copy

The pandas.DataFrame.transpose(*args, copy=False) creates a copy if all the columns of the original DataFrame are of the same data type; otherwise, it returns a view.

In the latter, if the original is updated, the transposed is also updated (applies in vice versa as well), but if a copy is created, editing the original leaves transposed unchanged (and vice versa).

In Example 2 above, all our columns on the original DataFrame are of the same data type (float); therefore, pandas create a view. Let’s redo Example 2 and update a cell to see the effect of this property.

import pandas as pd
# Creating a data frame using pandas as df2
data2  = {"Height_col1": [145.7, 179.8, 152.9],
"BMI_col2": [24.6, 22.8, 25]}
df2 = pd.DataFrame(data2, index=[f"Row{i}" for i in range(1,4)])
# Transpose the data frame to df2_transposed
df2_transposed = df2.transpose()
print('Original tabe:')
# Display/print the original data frame
print(df2)
print("Original table updated.")
# Update a cell in the original data frame
df2.at["Row1", "Height_col1"] = 166
print(df2)
# View the df2_transposed table. It is also updated.
print("After transposing (updated):")
print(df2_transposed)

Output (formatted for better view):

Since all the columns in the original table are of the same data type, updating the initial table automatically updates the transposed DataFrame. Creating transposed DataFrame as a view means it shares the same memory blocks as the original table.

Pandas create a copy if the columns are of different data types. In such a situation, the transposed object is allocated a separate memory area; if one is changed, the other remains unchanged.

Transposing pandas DataFrame using NumPy

The numpy.transpose(<dataframe>) can be used to transpose a DataFrame. Note that the function returns a transposed pandas DataFrame and not a NumPy array.

import pandas as pd
import numpy as np
# Creating a data frame using pandas as df2
data2  = {"Height_col1": [145.7, 179.8, 152.9],
"BMI_col2": [24.6, 22.8, 25]}
df2 = pd.DataFrame(data2, index=[f"Row{i}" for i in range(1,4)])
df2_transposed = np.transpose(df2)
print(type(df2_transposed))

Output:

<class 'pandas.core.frame.DataFrame'>