Pandas DataFrame t() and transpose() Method


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The Xarray library works with labeled multi-dimensional arrays and advanced analytics.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install xarray

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import xarray

DataFrame t() & transpose()

The T or transpose() method switches (transposes) the index and columns.

The syntax for this method is as follows:

DataFrame.transpose(*args, copy=False)
*argsThis parameter is for compatibility with NumPy.
copyIf True, the transformation occurs on a copy of the DataFrame/Series. If False, the transformation updates the original. This parameter is False, by default.

For this example, the countries.csv file reads in.

πŸ’‘ Note: Click here to download the CSV file. Move to the current working directory.

df = pd.read_csv('countries.csv').head(3)
print(df)

result1 = df.T
print(result1)

result2 = df.transpose()
print(result2)
  • Line [1] reads in the top three (3) rows of the comma-delimited CSV file. The output saves to df.
  • Line [2] outputs the DataFrame to the terminal.
  • Line [3] uses the T method to transpose the DataFrame. The output saves to result1.
  • Line [4] outputs result1 to the terminal.
  • Line [5] uses the transpose() method to transpose the DataFrame. The output saves to result2.
  • Line [6] outputs result2 to the terminal.

Output

df

 CountryCapitalPopulationArea
0GermanyBerlin83783942 357021
1FranceParis67081000 551695
2SpainMadrid47431256 498511

result1

 012
CountryGermanyFranceSpain
CapitalBerlinParisMadrid
Population83783942 67081000 47431256 
Area357021551695498511

result2

 012
CountryGermanyFranceSpain
CapitalBerlinParisMadrid
Population83783942 67081000 47431256 
Area357021551695498511

πŸ’‘ Note: The output from result1 and result2 are identical.


More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.