The Wayback Machine - https://web.archive.org/web/20240619002654/https://www.geeksforgeeks.org/python-pandas-dataframe-transpose/
Open In App

Pandas DataFrame transpose() Method: Swap Rows and Columns

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Pandas DataFrame is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns).

Arithmetic operations align on both row and column labels. It can be thought of as a dictionary-like container for the Series objects. This is the primary data structure of the Pandas.

Pandas DataFrame transpose() method transposes the index and columns of the DataFrame. It reflects the DataFrame over its main diagonal by writing rows as columns and vice-versa.

Syntax

DataFrame.transpose(*args, **kwargs) 

Parameter  

  • copy : If True, the underlying data is copied. Otherwise (default), no copy is made if possible. 
  • *args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy.

Returns : The transposed DataFrame

Examples

Let us look at some Python codes and understand the DataFrame transpose() method of Pandas library with these examples:

Example 1

Use the transpose() function to find the transpose of the given DataFrame.

Python3




# importing pandas as pd
import pandas as pd
  
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
                   'Age':[14, 25, 55, 8, 21]})
  
# Create the index
index_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H')
  
# Set the index
df.index = index_
  
# Print the DataFrame
print(df)


Output :

Example 1 Output

Now we will use the DataFrame transpose() function to find the transpose of the given DataFrame.

Python3




# return the transpose
result = df.transpose()
  
# Print the result
print(result)


Output :

Output

As we can see in the output, the DataFrame transpose() function has successfully returned the transpose of the given DataFrame.  

Example 2

Use the DataFrame transpose() function to find the transpose of the given DataFrame.

Python3




# importing pandas as pd
import pandas as pd
  
# Creating the DataFrame
df = pd.DataFrame({"A":[12, 4, 5, None, 1], 
                   "B":[7, 2, 54, 3, None], 
                   "C":[20, 16, 11, 3, 8], 
                   "D":[14, 3, None, 2, 6]}) 
  
# Create the index
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
  
# Set the index
df.index = index_
  
# Print the DataFrame
print(df)


Output :

Output

Now we will use the DataFrame transpose() function to find the transpose of the given DataFrame.

Python3




# return the transpose
result = df.transpose()
  
# Print the result
print(result)


Output :

As we can see in the output, the DataFrame transpose() function has successfully returned the transpose of the given DataFrame.



Similar Reads

Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
2 min read
Get the number of rows and number of columns in Pandas Dataframe
Pandas provide data analysts a variety of pre-defined functions to Get the number of rows and columns in a data frame. In this article, we will learn about the syntax and implementation of few such functions. Method 1: Using df.axes() Method axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument '0' fo
3 min read
Count the number of rows and columns of a Pandas dataframe
Pandas allow us to get the shape of the Dataframe by counting the number of rows and columns in the Dataframe. You can try various approaches to learn to count the number of rows and columns in a Pandas. Example: Input: {'name': ['Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura'], 'score': [98, 80, 60, 85, 49, 92], 'age': [20, 25, 22, 24
4 min read
Count the number of rows and columns of Pandas dataframe
In this article, we'll see how we can get the count of the total number of rows and columns in a Pandas DataFrame. There are different methods by which we can do this. Let's see all these methods with the help of examples. Example 1: We can use the dataframe.shape to get the count of rows and columns. dataframe.shape[0] and dataframe.shape[1] gives
2 min read
Find maximum values & position in columns and rows of a Dataframe in Pandas
In this article, we are going to discuss how to find the maximum value and its index position in columns and rows of a Dataframe. Create Dataframe to Find max values & position of columns or rows C/C++ Code import numpy as np import pandas as pd # List of Tuples matrix = [(10, 56, 17), (np.NaN, 23, 11), (49, 36, 55), (75, np.NaN, 34), (89, 21,
4 min read
Iterating over rows and columns in Pandas DataFrame
Iteration is a general term for taking each item of something, one after another. Pandas DataFrame consists of rows and columns so, to iterate over dataframe, we have to iterate a dataframe like a dictionary. In a dictionary, we iterate over the keys of the object in the same way we have to iterate in dataframe. In this article, we are using "nba.c
6 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Apply a function to single or selected columns or rows in Pandas Dataframe
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function. Apply a function to single row in Pandas DataframeHere, we will use different methods to apply a function to single rows by using Pandas dataframe. First lets create a
5 min read
Sort rows or columns in Pandas Dataframe based on values
In this article, Let's discuss how to Sort rows or columns in Pandas Dataframe based on values. Pandas sort_values() method sorts a data frame in Ascending or Descending order of passed Column. It's different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected. Syntax: DataFrame.sort_values(by,
7 min read
Get minimum values in rows or columns with their index position in Pandas-Dataframe
Let’s discuss how to find minimum values in rows & columns of a Dataframe and also their index position. a) Find the minimum value among rows and columns : Dataframe.min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the se
4 min read