jramm
jramm

Reputation: 6655

pandas - using the 'melt' function to reshape a table

I have the following table:

   Site Peril  ReturnPeriod  Min  Max  Mean
0  one  river            20  0.0  0.1  0.05
1  one  river           100  0.0  0.1  0.05
2  one  coast            20  2.0  5.3  4.00
3  one  coast           100  2.0  5.3  4.00
4  two  river            20  0.1  0.5  0.90
5  two  coast            20  0.3  0.5  0.80

I'm trying to reshape it to get to this:

           Peril:       river         coast      
  Site ReturnPeriod  Min Max Mean Min Max Mean
0 one            20  0.0 0.1 0.05 2.0 5.3 4.00 
1 one           100  0.0 0.1 0.05 2.0 5.3 4.00 
2 two            20  0.1 0.5 0.90 0.3 0.5 0.80

I think melt can take me halfway there but I'm having trouble getting the final output. Any ideas?

Upvotes: 1

Views: 622

Answers (1)

jramm
jramm

Reputation: 6655

I think that this may actually possible with just a call to pivot_table:

df.pivot_table(values = ['Min', 'Mean', 'Max'], rows = ['Site', 'ReturnPeriod'], cols = 'Peril')

I need to check it more thoroughly though.

Upvotes: 1

Related Questions