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
                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.
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.
To swap the rows and columns of a DataFrame in Pandas, use the DataFrame's transpose(~) method.
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).
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With