Transpose specific columns using python pandas

Question:

I want to transpose below data using python pandas. But I am not getting a proper solution as i want transpose specific columns.

Input Data Format-
enter image description here

Output Data Format-
enter image description here

Answers:

Try using melt

df = pd.DataFrame({"ID":["a","a","a","a"],
                   "Date":["date1","date2","date3","date4"],
                   "H1":[1,1,1,1],
                   "H2":[2,2,2,2],
                   "H3":[3,3,3,3],
                   "H4":[4,4,4,4]})
df1 = pd.melt(df,id_vars =['ID','Date'], value_vars =['H1','H2','H3','H4'])

Output of df;

enter image description here

Output of df1;

enter image description here

Answered By: Sachin Kohli
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.