For a pandas dataframe of:
defined by:
JavaScript
x
4
1
import pandas as pd
2
df = pd.DataFrame({'id':[1,2,3], 're_foo':[1,2,3], 're_bar':[4,5,6], 're_foo_baz':[0.4, 0.8, .9], 're_bar_baz':[.4,.5,.6], 'iteration':[1,2,3]})
3
display(df)
4
I want to reshape to the following format:
JavaScript
1
7
1
id, metric, value, iteration
2
1, foo , 1 , 1
3
1, bar , 4 , 1
4
1, foo_baz, 0.4 , 1
5
1, bar_baz, 0.4 , 0.4
6
7
A:
JavaScript
1
2
1
pd.wide_to_long(r, stubnames='re', i=['re_foo', 're_bar', 're_foo_baz', 're_bar_baz'], j='metric')
2
only results in a KeyError. How can I fix the reshape to work fine?
Advertisement
Answer
Here’s a way using stack
:
JavaScript
1
20
20
1
# fix column name, remove re_
2
df.columns = df.columns.str.replace(r're_', '')
3
4
# reshape dataframe into required format
5
df = df.set_index(['id','iteration']).stack().reset_index().rename(columns={'level_2':'metric', 0: 'value'})
6
7
id iteration metric value
8
0 1 1 foo 1.0
9
1 1 1 bar 4.0
10
2 1 1 foo_baz 0.4
11
3 1 1 bar_baz 0.4
12
4 2 2 foo 2.0
13
5 2 2 bar 5.0
14
6 2 2 foo_baz 0.8
15
7 2 2 bar_baz 0.5
16
8 3 3 foo 3.0
17
9 3 3 bar 6.0
18
10 3 3 foo_baz 0.9
19
11 3 3 bar_baz 0.6
20