'How can I transfer columns of a table to rows in python?

One ID can have multiple dates and results and I want each date and result column stacked sideways to be stacked into 1 date and 1 result row. How can I transfer columns of a table to rows?

[Table which needs to be transposed] enter image description here

[I want to change like this] enter image description here



Solution 1:[1]

This seems to work, not sure if it's the best solution:

    df2 = pd.concat([df.loc[:,['ID','Date','Result']],
             df.loc[:,['ID','Date1','Result1']].rename(columns={'Date1':'Date','Result1':'Result'}),
             df.loc[:,['ID','Date2','Result2']].rename(columns={'Date2':'Date','Result2':'Result'})
            ]).dropna().sort_values(by = 'ID')

It's just separating the dataframes, concatenating them together inline, removing the NAs and then sorting.

Solution 2:[2]

If you are looking to transpose data from pandas you could use pandas.DataFrame.pivot There are more examples there on the syntax.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fnqwejflqo
Solution 2 tylerjames