0

When I transpose a dataframe, the headers are considered as "index" by default. But I want it to be a column and not an index. How do I achieve this ?

import pandas as pd dict = {'col-a': [97, 98, 99], 'col-b': [34, 35, 36], 'col-c': [24, 25, 26]} df = pd.DataFrame(dict) print(df.T) 0 1 2 col-a 97 98 99 col-b 34 35 36 col-c 24 25 26 

Desired Output:

 0 1 2 3 0 col-a 97 98 99 1 col-b 34 35 36 2 col-c 24 25 26 

2 Answers 2

1

Try T with reset_index:

df=df.T.reset_index() print(df) 

Or:

df.T.reset_index(inplace=True) print(df) 

Both Output:

 index 0 1 2 0 col-a 97 98 99 1 col-b 34 35 36 2 col-c 24 25 26 

If care about column names, add this to the code:

df.columns=range(4) 

Or:

it=iter(range(4)) df=df.rename(columns=lambda x: next(it)) 

Or if don't know number of columns:

df.columns=range(len(df.columns)) 

Or:

it=iter(range(len(df.columns))) df=df.rename(columns=lambda x: next(it)) 

All Output:

 0 1 2 3 0 col-a 97 98 99 1 col-b 34 35 36 2 col-c 24 25 26 
Sign up to request clarification or add additional context in comments.

Comments

0

Use reset_index and then set default columns names:

df1 = df.T.reset_index() df1.columns = np.arange(len(df1.columns)) print (df1) 0 1 2 3 0 col-a 97 98 99 1 col-b 34 35 36 2 col-c 24 25 26 

Another solution:

print (df.rename_axis(0, axis=1).rename(lambda x: x + 1).T.reset_index()) #alternative #print (df.T.rename_axis(0).rename(columns = lambda x: x + 1).reset_index()) 0 1 2 3 0 col-a 97 98 99 1 col-b 34 35 36 2 col-c 24 25 26 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.