From Column headers to column value

Viewed 36

I transpose a DF which columns where dates and rows variables. So it's now has the forms of Dates as column head (but I want them to be a column value named Date) and the rows are now columns.

How can I move from column headers to column vuales so the date which was originally header and is now and index transform it into a new variables which has the name "Date", thank you

Current:

df
   c  d
a  1  2
b  3  4

I would like to get this:

df
  col1 col2  col3
0    a    c     1
1    a    d     2
2    b    c     3
3    b    d     4
2 Answers

You can try this. You might want to rename the column after

df.stack().reset_index()

to rename your column you can also try using the rename()

df.stack().reset_index().rename(columns= {'level_0':'col1','level_1':'col2',0:'col3'})

Current df

df = pd.DataFrame([
    {'c': 1, 'd': 2},
    {'c': 3, 'd': 4}], index=['a', 'b'])

  c d 
a 1 2 
b 3 4

Desired df

df = df.stack().reset_index()
df.columns = ['col1', 'col2', 'col3']

enter image description here

Related