Transposing a pandas dataframe is an important part of manipulating and exploring data. It involves switching the rows and columns in order to view and analyze the data from another perspective. To transpose a pandas dataframe, you will need to use the .T method. This operation can be done as follows:
Create a dataframe with pandas
Let's first create a dataframe with pandas
import pandas as pd
data = {'Age':[21,26,82,15,28],
'Id':['jch2c1','63jc2h','hg217d','hj127b','edew32'],
'weight':[120,148,139,156,129],
'Gender':['male','male','female','male','female'],
'Country':['France','USA','USA','Germany','USA']}
df = pd.DataFrame(data=data,index=['A','B','C','D','E'])
returns
Age Id weight Gender Country
A 21 jch2c1 120 male France
B 26 63jc2h 148 male USA
C 82 hg217d 139 female USA
D 15 hj127b 156 male Germany
E 28 edew32 129 female USA
Transpose a dataframe
A simple solution for transposing a dataframe is to use the following code
df.T
returns
A B C D E
Age 21 26 82 15 28
Id jch2c1 63jc2h hg217d hj127b edew32
weight 120 148 139 156 129
Gender male male female male female
Country France USA USA Germany USA
To make it more permanent
df = df.T
Transpose a dataframe using transpose()
With option copy = False
Another solution is to use
new_df = df.transpose()
Note that by default transpose() has the option copy = False.
returns
A B C D E
Age 21 26 82 15 28
Id jch2c1 63jc2h hg217d hj127b edew32
weight 120 148 139 156 129
Gender male male female male female
Country France USA USA Germany USA
Then if the original dataframe is modified:
df.loc['A','weight'] = -9999
gives
Age Id weight Gender Country
A 21 jch2c1 -9999 male France
B 26 63jc2h 148 male USA
C 82 hg217d 139 female USA
D 15 hj127b 156 male Germany
E 28 edew32 129 female USA
the transposed dataframe is not affected since copy = False
A B C D E
Age 21 26 82 15 28
Id jch2c1 63jc2h hg217d hj127b edew32
weight 120 148 139 156 129
Gender male male female male female
Country France USA USA Germany USA
With option copy = True
Now with the option copy = True:
new_df = df.transpose(copy=True)
if the original dataframe is modified:
df.loc['A','weight'] = -9999
returns
Age Id weight Gender Country
A 21 jch2c1 -9999 male France
B 26 63jc2h 148 male USA
C 82 hg217d 139 female USA
D 15 hj127b 156 male Germany
E 28 edew32 129 female USA
the transposed dataframe is ALSO affected:
A B C D E
Age 21 26 82 15 28
Id jch2c1 63jc2h hg217d hj127b edew32
weight -9999 148 139 156 129
Gender male male female male female
Country France USA USA Germany USA
References
Links | Site |
---|---|
pandas.DataFrame.transpose | pandas.pydata.org |
pandas: Transpose DataFrame (swap rows and columns) | pandas.pydata.org |