Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to transpose from df1 to df2 in pandas. Can anyone help me with the codes that transpose data from wide to long? Thanks

df1:

  id     1/22/20    1/23/20 1/24/20 1/25/20

   a        1       2       3       4  

   b        3       4       5       6

   c        5       6       7       8

df2:

  Date      a       b       c

  1/22/20   1       3       5

  1/23/20   2       4       6

  1/24/20   3       5       7

  1/25/20   4       6       8

1 Answer

0 votes
by (36.8k points)

Using df.set_index and df.T and df.rename_axis

df = df.set_index('id').T.rename_axis("Date", axis=1)

print(df)

Output:

Date a b c

1/22/20 1 3 5

1/23/20 2 4 6

1/24/20 3 5 7

1/25/20 4 6 8

If you are a beginner and want to know more about Python the do check out the python for data science course 

Browse Categories

...