How to Transpose a Pandas DataFrame without Index


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.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Drop Columns in Pandas
How to Drop Rows in Pandas DataFrame Based on Condition
How to Drop Rows that Contain a Specific Value in Pandas

Leave a Reply

Your email address will not be published.