Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert index and columns in a pandas DataFrame

Tags:

python

pandas

I have a pandas DataFrame with a single row:

         10  20  30  70
data1:  2.3   5   6   7

I want to reindex the frame so that the column values (10, 20, 30, 70) become index values and the data becomes the column:

    data1:
10     2.3
20     5.0
30     6.0
70     7.0

How do I achieve this?

like image 438
nom-mon-ir Avatar asked Jun 12 '13 22:06

nom-mon-ir


People also ask

How do you invert rows and columns in Pandas?

Pandas DataFrame. transpose() is a library function that transpose index and columns. The transpose reflects the DataFrame over its main diagonal by writing rows as columns and vice-versa. Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of DataFrame.

How do you reverse an index in a data frame?

Using reindex() function to Reverse Row Reverse rows of the data frame using reindex() Function. The pandas dataframe. reindex() function concatenates the dataframe to a new index with optional filling logic, placing NA/NaN at locations that have no value in the previous index.

How do I change an index to a column?

In order to set index to column in pandas DataFrame use reset_index() method. By using this you can also set single, multiple indexes to a column. If you are not aware by default, pandas adds an index to each row of the pandas DataFrame.


1 Answers

You're looking for the transpose (T) method:

In [11]: df
Out[11]:
         10  20  30  70
data1:  2.3   5   6   7

In [12]: df.T
Out[12]:
    data1:
10     2.3
20     5.0
30     6.0
70     7.0
like image 184
Andy Hayden Avatar answered Sep 19 '22 08:09

Andy Hayden