Write a program in Python to transpose the index and columns in a given DataFrame

PythonPandasServer Side ProgrammingProgramming

Input

Assume you have a DataFrame, and the result for transpose of index and columns are,

Transposed DataFrame is
  0 1
0 1 4
1 2 5
2 3 6

Solution 1

  • Define a DataFrame

  • Set nested list comprehension to iterate each element in the two-dimensional list data and store it in result.

result = [[data[i][j] for i in range(len(data))] for j in range(len(data[0]))
  • Convert the result to DataFrame,

df2 = pd.DataFrame(result)

Example

Let us see the complete implementation to get a better understanding −

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data)
print("Original DataFrame is\n", df)
result = [[data[i][j] for i in range(len(data))] for j in range(len(data[0]))]
df2 = pd.DataFrame(result)
print("Transposed DataFrame is\n", df2)

Output

Original DataFrame is
  0 1 2
0 1 2 3
1 4 5 6
Transposed DataFrame is
  0 1
0 1 4
1 2 5
2 3 6

Solution 2

  • Define a DataFrame

  • Apply transpose method either df.T or df.transpose() to the DataFrame.

df.transpose() # or df.T

Example

Let us see the complete implementation to get a better understanding −

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data)
print("Original DataFrame is\n", df)
print("Transposed DataFrame is\n", df.transpose())

Output

Original DataFrame is
  0 1 2
0 1 2 3
1 4 5 6
Transposed DataFrame is
  0 1
0 1 4
1 2 5
2 3 6

Solution 3

  • Define a DataFrame

  • Zip method returns an iterator of tuples. Apply to unzip to the two-dimensional list using * and zip it. It is defined below,

result = zip(*data)
  • Convert the result to DataFrame,

df2 = pd.DataFrame(result)

Example

Let us see the complete implementation to get a better understanding −

import pandas as pd
data = [[1,2,3],[4,5,6]]
df = pd.DataFrame(data)
print("Original DataFrame is\n", df)
result = zip(*data)
df2 = pd.DataFrame(result)
print("Transposed DataFrame is\n", df2)

Output

Original DataFrame is
  0 1 2
0 1 2 3
1 4 5 6
Transposed DataFrame is
  0 1
0 1 4
1 2 5
2 3 6
raja
Published on 11-Feb-2021 09:58:36
Advertisements