Reputation: 387
I am working with pandas data frames. Suppose I have
df = pd.DataFrame({'name':['a', 'b', 'c'], 'x':[1,2,3], 'y':[4,5,6]})
and I want to have something looking like
import numpy as np
arrays = [np.array(['a', 'a', 'b', 'b', 'c', 'c']),np.array(['x', 'y','x', 'y','x', 'y'])]
df1 = pd.DataFrame([1,4,2,5,3,6], index=arrays)
But to keep the 'name' heading.
(apologies I'm not sure how to make the code bits compile here and show the data frames explicitly).
For some reason I am struggling to do this with my (much larger) data set.
What I have tried:
But this gives me a 'groupie' object and I don't know what to do with it.
Not working because I'm trying to keep the 'names' fixed.
This is giving me
0 name a
x 1
y 4
1 name b
x 2
y 5
2 name c
x 3
y 6
dtype: object
i.e. a single layer index object rather than double layer.
Any help would be much appreciated.
Upvotes: 1
Views: 166
Reputation: 71687
Use:
df1 = df.set_index('name').stack().to_frame()
# print(df1)
0
name
a x 1
y 4
b x 2
y 5
c x 3
y 6
Upvotes: 1