How to switch columns rows in a pandas dataframe
Asked Answered
D

2

20

I have the following dataframe:

                                0       1
0                 enrichment_site   value
1                    last_updated   value
2                     image_names   value
3                 shipping_weight   value
4                        ean_gtin   value
5                        stockqty   value
6                      height__mm   value
7                    availability   value
8                             rrp   value
9                             sku   value
10                     price_band   value
11                           item   value

I tried with pivot table

test.pivot(index=index, columns='0', values='1')

but I get the following error:

KeyError: '1'

any alternative to pivot table to do this?

Disputant answered 27/7, 2015 at 16:15 Comment(1)
What is the desired result? What is the value of index?Mi
D
61

You can use df = df.T to transpose the dataframe. This switches the dataframe round so that the rows become columns.

You could also use pd.DataFrame.transpose().

Dangerous answered 27/7, 2015 at 16:45 Comment(0)
S
3

When using pd.DataFrame.transpose (as suggested by Jamie Bull), be sure to actually write

pd.DataFrame.transpose()

...without the brackets, it didn't work for me.

Starbuck answered 9/2, 2018 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.