Pandas DataFrame t() and transpose() Method – Be on the Right Side of Change (original) (raw)


Preparation

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

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


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

The syntax for this method is as follows:

DataFrame.transpose(*args, copy=False)

*args This parameter is for compatibility with NumPy.
copy If 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)

Output

df

| | Country | Capital | Population | Area | | | --------- | ------- | ---------- | -------- | ------ | | 0 | Germany | Berlin | 83783942 | 357021 | | 1 | France | Paris | 67081000 | 551695 | | 2 | Spain | Madrid | 47431256 | 498511 |

result1

| | 0 | 1 | 2 | | | ---------- | -------- | -------- | -------- | | Country | Germany | France | Spain | | Capital | Berlin | Paris | Madrid | | Population | 83783942 | 67081000 | 47431256 | | Area | 357021 | 551695 | 498511 |

result2

| | 0 | 1 | 2 | | | ---------- | -------- | -------- | -------- | | Country | Germany | France | Spain | | Capital | Berlin | Paris | Madrid | | Population | 83783942 | 67081000 | 47431256 | | Area | 357021 | 551695 | 498511 |

💡 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.