I have a data-frame like as shown below
df = pd.DataFrame({
'subject_ID':[1,2,3,4,5],
'date_visit':['1/1/2020','3/3/2200','13/11/2100','24/05/2198','30/03/2071'],
'a11fever':['Yes','No','Yes','Yes','No'],
'a12diagage':[36,34,42,40,np.nan],
'a12diagyr':[2021,3213,2091,4567,8901],
'a12diagyrago':[6,np.nan,9,np.nan,np.nan]})
I would like to transform the dataframe where the sample output for one subject looks like as shown below
Though I was able to do this successfully using pd.melt
and stack
, I couldn't do the same using wide_long
.
pd.melt(df, id_vars =['subject_ID','date_visit'], value_vars =['a11fever', 'a12diagage', 'a12diagyr','a12diagyrago']) # works fine
pd.wide_to_long(df, stubnames=['measurement', 'val'],i=(['subject_ID','date_visit']), j='grp').sort_index(level=0) # returns 0 records
df.set_index(['subject_ID','date_visit']).stack().reset_index() #works fine
another question I have is,
a) Do we always have to mention all the column names that we would like to transform under value_vars
section of pd.melt
. My real data will have more than 120 columns. So do I have to mention all of them here?
Can you also help me with this on how to do it using wide_long
?