Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping Axes in Pandas

What is the most efficient way to swap the axes of a Pandas Dataframe?

For example, how could df1 be converted to df2 below?

In [2]: import pandas as pd

In [3]: df1 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})

In [4]: df1
Out[4]: 
   one  two
0    1    4
1    2    3
2    3    2
3    4    1

In [5]: df2 = pd.DataFrame({0 : [1,4], 1 : [2,3], 2 : [3,2], 3 : [4,1]}, index=['one','two'])

In [6]: df2
Out[6]: 
     0  1  2  3
one  1  2  3  4
two  4  3  2  1
like image 966
Clayton Avatar asked Apr 30 '13 13:04

Clayton


People also ask

How do I flip axis in DataFrame pandas?

Example #1: Use swapaxes() function to swap the axes of the dataframe. Output : Example #2: Use swapaxes() function to swap the index and column axes with each other.

How do I change the axis in a data frame?

The set_axis() function is used to assign desired index to given axis. Indexes for column or row labels can be changed by assigning a list-like or Index. The values for the new index. The axis to update.

How do you swap columns in a data frame?

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

How do you switch columns and indexes in Python?

Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of pandas. DataFrame . Neither method changes the original object but returns a new object with the rows and columns swapped (= transposed object).


1 Answers

Take a look at transpose

In [4]: df1.T
Out[4]: 
     0  1  2  3
one  1  2  3  4 
two  4  3  2  1
like image 93
waitingkuo Avatar answered Sep 21 '22 23:09

waitingkuo