Home > Software design >  Switch rows and columns of dataframe, without using transpose function
Switch rows and columns of dataframe, without using transpose function

Time:05-12

I need to switch the rows and columns of a dataframe without using the transpose function (df.T), this is the code I wrote so far.

def transpose(matrix):
    
    transposed = pd.DataFrame()
    
    for i,j in matrix.iteritems():
        transposed.iloc[j,i] = matrix.iloc[j,i]
    
    return transposed

This code is giving the error: IndexError: positional indexers are out-of-bounds

After trying for a while, this is my new code:

def transpose(matrix):
   
    transposed = matrix.copy()
    
    for i,j in matrix.iteritems():
        transposed.iat[i, j] = matrix.iat[j, i]
    
    return transposed

This is giving ValueError: iAt based indexing can only have integer indexers.

Changing iat to iloc, loc or at doesn't work.

CodePudding user response:

All problem can be because iteritems() gives different values than you expect.
It gives column's name and Series with row's number and value in cell.

It can be simpler to use normal for-loops with range(width), range(height)

And code need to create DataFrame with expected size before you will try to put values

def transpose(matrix):
    
    h,w = matrix.shape[:2]
    
    transposed = pd.DataFrame(np.zeros((w,h)))
    
    for y in range(h):
        for x in range(w):
            transposed.iloc[x,y] = matrix.iloc[y,x]
    
    return transposed

# --- main ---

import pandas as pd
import numpy as np

data = [ 
    [1,2,3], 
    [4,5,6], 
    [7,8,9] 
]  # rows

df = pd.DataFrame(data, columns=['A', 'B', 'C'])

print(df)

df = transpose(df)

print(df)

Results:

   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

     0    1    2
0  1.0  4.0  7.0
1  2.0  5.0  8.0
2  3.0  6.0  9.0

CodePudding user response:

Sooo, after trying for a very long time, this is the code that works! Sharing in case somebody might find it helpful :)

def transpose(matrix):

    transposed = pd.DataFrame(index=matrix.columns, columns=matrix.index)
    
    for i,j in matrix.items():
        for x,y in j.items():
            transposed.at[i] = j
    
    return transposed
  • Related