1 回答
TA贡献1824条经验 获得超5个赞
reset_index那么我们来尝试一下melt:
param_list = ['param1','param2','param3']
s=(df.rename_axis(['country','type'])
.reset_index()
)
mask=s['type'].isin(param_list)
s['country'] = s['type'].mask(mask).ffill()
out = s[mask].melt(['country','type'], var_name='year')
输出:
country type year value
0 England param1 2017 20
1 England param2 2017 25
2 England param3 2017 25
3 England param1 2017 10
4 England param2 2017 20
5 England param3 2017 30
6 US param1 2017 3
7 US param2 2017 3
8 US param3 2017 4
9 US param1 2017 10
10 US param2 2017 20
11 US param3 2017 30
12 England param1 2018 30
13 England param2 2018 35
14 England param3 2018 15
15 England param1 2018 25
16 England param2 2018 25
17 England param3 2018 0
18 US param1 2018 5
19 US param2 2018 10
20 US param3 2018 5
21 US param1 2018 25
22 US param2 2018 25
23 US param3 2018 0
24 England param1 2019 40
25 England param2 2019 45
26 England param3 2019 5
27 England param1 2019 10
28 England param2 2019 20
29 England param3 2019 30
30 US param1 2019 10
31 US param2 2019 10
32 US param3 2019 10
33 US param1 2019 10
34 US param2 2019 20
35 US param3 2019 30
添加回答
举报