vs_93
vs_93

Reputation: 85

Make dataframe rows as index

I have a dataframe like :

 country  indicator y1  y2    y3   y4
0   abc    a       0.1  0.1   0.1   0.1
1   abc    b       0.1  0.2   0.4   0.1
2   wed    a       0.1  0.1   0.1   0.1
3   wed    b       0.7  0.1   0.6   0.1

I need something like:

 country    y         a    b
0   abc    y1       0.1  0.1
           y2       0.1  0.2 
           y3       0.1  0.1  
           y4       0.7  0.1  
1   wed    y1       0.1  0.1
           y2       0.1  0.2 
           y3       0.1  0.1  
           y4       0.7  0.1  

The solutions point to transpose but i can't seem to convert them exactly as needed.

Upvotes: 2

Views: 67

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

df.set_index(['country','indicator']).stack().unstack(1)

Output:

indicator     a    b
country             
abc     y1  0.1  0.1
        y2  0.1  0.2
        y3  0.1  0.4
        y4  0.1  0.1
wed     y1  0.1  0.7
        y2  0.1  0.1
        y3  0.1  0.6
        y4  0.1  0.1

Upvotes: 4

Related Questions