2

I am having following dataframe:

A,B,C
1,2,3

I have to convert above dataframe like following format:

cols,vals
A,1
B,2
c,3

How to create column names as a new column in pandas?

1 Answer 1

2

You can transpose by T:

import pandas as pd

df = pd.DataFrame({'A': {0: 1}, 'C': {0: 3}, 'B': {0: 2}})

print (df)
   A  B  C
0  1  2  3

print (df.T)
   0
A  1
B  2
C  3

df1 = df.T.reset_index()
df1.columns = ['cols','vals']
print (df1)
  cols  vals
0    A     1
1    B     2
2    C     3

If DataFrame has more rows, you can use:

import pandas as pd

df = pd.DataFrame({'A': {0: 1, 1: 9, 2: 1}, 
                  'C': {0: 3, 1: 6, 2: 7}, 
                  'B': {0: 2, 1: 4, 2: 8}})

print (df)
   A  B  C
0  1  2  3
1  9  4  6
2  1  8  7

df.index = 'vals' + df.index.astype(str)

print (df.T)
   vals0  vals1  vals2
A      1      9      1
B      2      4      8
C      3      6      7

df1 = df.T.reset_index().rename(columns={'index':'cols'})
print (df1)

  cols  vals0  vals1  vals2
0    A      1      9      1
1    B      2      4      8
2    C      3      6      7
Sign up to request clarification or add additional context in comments.

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.