Meep
Meep

Reputation: 387

Trying to pivot by keeping a fixed column

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:

  1. Using df.groupby('name')

But this gives me a 'groupie' object and I don't know what to do with it.

  1. Using .pivot

Not working because I'm trying to keep the 'names' fixed.

  1. Using .stack

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

Answers (1)

Shubham Sharma
Shubham Sharma

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

Related Questions