GSA
GSA

Reputation: 793

How do I change the shape of my data in pandas

I have some data in a pandas DataFrame. I have provided a sample of the data below:

        V1          V2          V3          V4          V5          V6          V7          V8
ID                              
B7393   7.418801    0.805774    0.837428    0.866967    0.773911    0.825854    0.858694    0.763436
C7096   7.418801    0.857844    0.859367    0.861062    0.804877    0.829015    0.852472    0.763436

What I want to do is change how the data is presented into the sample below. How do I go about doing that? I'm new to python and still learning.

ID
B7393       
    V1  7.418801
    V2  0.805774
    V3  0.837428
    V4  0.866967
    V5  0.773911
    V6  0.825854
    V7  0.858694
    V8  0.763436
C7096       
    V1  7.418801
    V2  0.857844
    V3  0.859367
    V4  0.861062
    V5  0.804877
    V6  0.829015
    V7  0.852472
    V8  0.763436

Upvotes: 0

Views: 266

Answers (2)

Pablo C
Pablo C

Reputation: 4761

You can directly use pandas.DataFrame.stack here:

>>> df.stack()
ID       
B7393  V1    7.418801
       V2    0.805774
       V3    0.837428
       V4    0.866967
       V5    0.773911
       V6    0.825854
       V7    0.858694
       V8    0.763436
C7096  V1    7.418801
       V2    0.857844
       V3    0.859367
       V4    0.861062
       V5    0.804877
       V6    0.829015
       V7    0.852472
       V8    0.763436
dtype: float64

Upvotes: 1

semblable
semblable

Reputation: 783

Why not use Pandas' wide_to_long()?

pd.wide_to_long(df.reset_index(), stubnames=['V'], i=['index'], j='V_thing')

or melt()?

pd.melt(
    df.reset_index(),
    id_vars =['index'],
    value_vars =['V'+str(i) for i in list(range(1,9))]
).set_index('index')

Upvotes: 0

Related Questions