1

convert header to one column and multiple columns to another column in Pandas DF:

DF:

df = pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns =["2000","2001","2002" ])
df.index = pd.Index(["A","B","C"],name = "random")
df

OP:

        2000    2001    2002
random          
A        1       5       4
B        8       2       2
C        0       3       6

Expected OP - Unique Index and 2 columns:

     0     1    

0   2000   1
1   2000   8
2   2000   0
3   2001   5
4   2001   2
5   2001   3
6   2002   4
7   2002   2
8   2002   6

I have an iterative approach with df.iterrows which is taking a long time for a huge DF, is there a more pandas way to do this? Any suggestions would be great.

data_person
  • 4,194
  • 7
  • 40
  • 75

1 Answers1

1
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns =["2000","2001","2002" ])
df.index = pd.Index(["A","B","C"],name = "random")

df=pd.melt(df, value_vars=["2000","2001","2002" ])
print(df)

# output
  variable  value
0     2000      5
1     2000      1
2     2000      2
3     2001      5
4     2001      4
5     2001      6
6     2002      4
7     2002      9
8     2002      3
some_programmer
  • 3,268
  • 4
  • 24
  • 59