I have question about transposing (melting or stacking?) and joining data sets.
I have 3 dataframes (above) and I want to transform and join them to make the outcome that I have on the right.
I've been reading about stack, melt, transpose, and merge and am a bit confused.
Advice on getting the desired outcome?
Thanks!
Starting with:
df1 = df1.set_index('Country')
2012 2013 2014
Country
AFG 1 4 7
AGO 2 5 8
ALF 3 6 9
df2 = df1.mul(2)
df3 = df1.mul(3)
You can .stack()
and pd.concat()
:
df = pd.concat([df1.stack(), df2.stack(), df3.stack()], axis=1)
df.columns = ['A', 'B', 'C']
df.reset_index().rename(columns={'level_1': 'Year'})
Country Year A B C
0 AFG 2012 1 2 3
1 AFG 2013 4 8 12
2 AFG 2014 7 14 21
3 AGO 2012 2 4 6
4 AGO 2013 5 10 15
5 AGO 2014 8 16 24
6 ALF 2012 3 6 9
7 ALF 2013 6 12 18
8 ALF 2014 9 18 27
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.