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
and now I’d like to transpose two columns to rows like below. Could you let me know how to do that?
Thanks,
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
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])
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
and now I’d like to transpose two columns to rows like below. Could you let me know how to do that?
Thanks,
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
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])