Reputation: 85
I have a dataframe of style:
item1 item2 item3
idx1 val1 val1 val1
idx2 val2 val2 val2
idx3 val3 val3 val3
idx4 val4 val4 val4
idx5 val5 val5 val5
I'm trying to swap it around so that it looks like this:
idx1 idx2 idx3 idx4 idx5
item1 val1 val2 val3 val4 val5
item2 val1 val2 val3 val4 val5
item3 val1 val2 val3 val4 val5
Essentially, I want the indexes to become the columns and the columns to become the index. However when I try doing something like df = pivot_table(df, index=df.columns, columns=df.index)
I get an error that says Grouper and axis must be same length
I'm not certain how to swap these around. Any help would be appreciated on what I'm doing wrong.
Upvotes: 0
Views: 63
Reputation: 6908
You can achieve this by transposing the dataframe, either by referring to its transpose attribute (df.T
) or by using its transpose method (df.transpose()
):
>>> df
item1 item2 item3
idx1 val1 val1 val1
idx2 val2 val2 val2
idx3 val3 val3 val3
idx4 val4 val4 val4
idx5 val5 val5 val5
>>> df = df.T
>>> df
idx1 idx2 idx3 idx4 idx5
item1 val1 val2 val3 val4 val5
item2 val1 val2 val3 val4 val5
item3 val1 val2 val3 val4 val5
Upvotes: 3