Search code examples
pythonstacktranspose

How to stack columns to rows in Python?


For example, the data structrue is like below.

import pandas as pd

source={
'Genotype1':["CV1","CV1","CV1","CV1","CV1"], 
'Grain_weight1':[25,26,30,31,29], 
'Genotype2':["CV2","CV2", "CV2","CV2","CV2"],
'Grain_weight2':[29,32,33,32,30]
}

df=pd.DataFrame(source, index=[1,2,3,4,5])
df

enter image description here

and now I'd like to transpose two columns to rows like below. Could you let me know how to do that?

enter image description here

Thanks,


Solution

  • It is not transposing. This is actually vertical stacking. You can achieve the same by the following code:

    pd.DataFrame(np.vstack([df[df.columns[2:].to_list()].to_numpy(),
               df[df.columns[:2].to_list()].to_numpy()]), columns = df.columns[:2])