Travis
Travis

Reputation: 687

Edit Pandas Pivot Table

In my pandas dataframe I have the following table loaded from a csv, call it table.csv

x         |  w         |  y  |  z  
indexval1 | stringval1 |  b1 |  c1
indexval2 | stringval2 |  b2 |  c2 
indexval3 | stringval3 |  b3 |  c3
indexval4 | stringval4 |  b4 |  c4

Here is the code I run to pivot...

df = pandas.read_csv("table.csv")
df.pivot_table(values = ["y", "z"] index = "x" columns = "w")
df.fillna(value = 00)

Which looks like this:

-----    | y         | z          | y          | z  
w        |stringval1 | stringval1 | stringval2 | stringval2
x        |           |            |            |
indexval1| b1        | c1         | 00         | 00  
indexval2| 00        | 00         | b2         | c2  
indexval3| 00        | 00         | 00         | 0  
indexval4| 00        | 00         | 00         | 00  

How can I edit it to look like this:

    w        |stringval1 | stringval1 | stringval2 | stringval2  
    -----    | y         | z          | y          | z  
    x        |           |            |            |
    indexval1| b1        | c1         | 00         | 00  
    indexval2| 00        | 00         | b2         | c2  
    indexval3| 00        | 00         | 00         | 0  
    indexval4| 00        | 00         | 00         | 00  

Upvotes: 2

Views: 436

Answers (1)

jezrael
jezrael

Reputation: 863176

I think you need swaplevel, because columns is Multiindex:

df = df.swaplevel(0,1, axis=1)

Upvotes: 3

Related Questions