Table of Contents
To transpose a Pandas DataFrame without Index, use the DataFrame.T method, which will transpose the rows and columns of the DataFrame, as well as the column labels and index, while preserving the values in the DataFrame. This is helpful when pivoting the data or changing the orientation of the DataFrame.
You can use the following syntax to transpose a pandas DataFrame and leave out the index:
df.set_index('first_col').T
This simply sets the first column of the DataFrame as the index and then performs the transpose.
The following example shows how to use this syntax in practice.
Example: Transpose Pandas DataFrame without Index
Suppose we have the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F'], 'points': [18, 22, 19, 14, 14, 11], 'assists': [5, 7, 7, 9, 12, 9]}) #view DataFrame print(df) team points assists 0 A 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9
If we transpose the DataFrame, the index values will be shown along the top:
#transpose DataFrame
df.T
0 1 2 3 4 5
team A B C D E F
points 18 22 19 14 14 11
assists 5 7 7 9 12 9
To transpose the DataFrame without the index, we can first use the set_index() function:
#transpose DataFrame without index
df.set_index('team').T
team A B C D E F
points 18 22 19 14 14 11
assists 5 7 7 9 12 9
Notice that the index values are no longer shown along the top of the transposed DataFrame.