How to stack columns to rows in Python?

Question:

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,

Asked By: Jin.W.Kim

||

Answers:

You could do the following:

result = pd.concat(
    [df[["Genotype1", "Grain_weight1"]],
     df[["Genotype2", "Grain_weight2"]].rename(lambda c: f"{c[:-1]}1", axis=1)],
    ignore_index=True
)

Result for the sample:

  Genotype1  Grain_weight1
0       CV1             25
1       CV1             26
2       CV1             30
3       CV1             31
4       CV1             29
5       CV2             29
6       CV2             32
7       CV2             33
8       CV2             32
9       CV2             30
Answered By: Timus

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]) 
Answered By: SAMIR ORUJOV
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.