I would like to add a new level to the index of a dataframe, based on columns name. How can i do that ?
JavaScript
x
6
1
df
2
home city
3
A -0.166809 0.213299
4
B -0.040300 0.034583
5
C -0.002245 0.001058
6
Desired result
JavaScript
1
7
1
A home -0.166809
2
city 0.213299
3
B home -0.040300
4
city 0.034583
5
C home -0.002245
6
city 0.001058
7
I can build the multiindex with this but how can i create a new dataframe and map the data ?
JavaScript
1
5
1
idx = pd.MultiIndex.from_product ([df.index, df.columns])
2
pd.DataFrame(df.values, ix)
3
4
ValueError: Shape of passed values is (3, 2), indices imply (6, 2)
5
Advertisement
Answer
You can use df.stack()
JavaScript
1
10
10
1
print(df.stack())
2
3
A home -0.166809
4
city 0.213299
5
B home -0.040300
6
city 0.034583
7
C home -0.002245
8
city 0.001058
9
dtype: float64
10
Back to your code, you can try numpy.ravel
to flatten the df.values
to match the idx
shape (idx
has 6 items, df.values
only return rows which are 3)
JavaScript
1
3
1
idx = pd.MultiIndex.from_product([df.index, df.columns])
2
df = pd.DataFrame(df.values.ravel(), idx)
3
JavaScript
1
10
10
1
print(df)
2
3
0
4
A home -0.166809
5
city 0.213299
6
B home -0.040300
7
city 0.034583
8
C home -0.002245
9
city 0.001058
10