I have data in the below format.
Input
From To Zone 1 Zone 2 Zone 3 Zone 4 Zone 5
10.1 20 0.45 0.45 0.35 0.45 0.45
20.1 40 0.45 0.45 0.45 0.45 0.70
40.1 50 0.50 0.50 0.55 0.55 0.55
50.1 250 0.75 0.79 0.79 0.80 0.79
Desired Output
From To Kg Attribute Value
10.1 20 0.5 Zone 1 0.45
10.1 20 0.5 Zone 2 0.45
10.1 20 0.5 Zone 3 0.35
10.1 20 0.5 Zone 4 0.45
10.1 20 0.5 Zone 5 0.45
20.1 40 0.5 Zone 1 0.45
20.1 40 0.5 Zone 2 0.45
20.1 40 0.5 Zone 3 0.45
20.1 40 0.5 Zone 4 0.45
20.1 40 0.5 Zone 5 0.70
How can this be done in pandas python?
You can set From and To as index and use stack().
(
df.set_index(['From', 'To']).stack().to_frame('Value')
.rename_axis(['From', 'To', 'Attribute'])
.assign(Kg=0.5)
.reset_index()
)
From To Attribute Value Kg
0 10.1 20 Zone1 0.45 0.5
1 10.1 20 Zone2 0.45 0.5
2 10.1 20 Zone3 0.35 0.5
3 10.1 20 Zone4 0.45 0.5
4 10.1 20 Zone5 0.45 0.5
5 20.1 40 Zone1 0.45 0.5
6 20.1 40 Zone2 0.45 0.5
7 20.1 40 Zone3 0.45 0.5
8 20.1 40 Zone4 0.45 0.5
9 20.1 40 Zone5 0.70 0.5
10 40.1 50 Zone1 0.50 0.5
11 40.1 50 Zone2 0.50 0.5
12 40.1 50 Zone3 0.55 0.5
13 40.1 50 Zone4 0.55 0.5
14 40.1 50 Zone5 0.55 0.5
15 50.1 250 Zone1 0.75 0.5
16 50.1 250 Zone2 0.79 0.5
17 50.1 250 Zone3 0.79 0.5
18 50.1 250 Zone4 0.80 0.5
19 50.1 250 Zone5 0.79 0.5
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.