Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to switch columns rows in a pandas dataframe

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?

like image 208
Blue Moon Avatar asked Jul 27 '15 16:07

Blue Moon


People also ask

How do I flip columns and rows in pandas?

Pandas DataFrame: transpose() functionThe transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. If True, the underlying data is copied. Otherwise (default), no copy is made if possible.

How do I swap columns in pandas DataFrame?

Swapping two dataframe columns is like interchanging the values of two columns. Pandas provides us a special feature or method called DataFrame. reindex() which is used for swapping two columns at a time, it takes a list of columns that needs to be swapped inside it as a parameter.

How do you switch rows in a DataFrame in Python?

To swap the rows and columns of a DataFrame in Pandas, use the DataFrame's transpose(~) method.

How do you flip the order of rows in pandas?

Reversing the rows of a data frame in pandas can be done in python by invoking the loc() function. The panda's dataframe. loc() attribute accesses a set of rows and columns in the given data frame by either a label or a boolean array.


1 Answers

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().

like image 50
Jamie Bull Avatar answered Sep 22 '22 08:09

Jamie Bull