Home > Software design >  How to turn column header into pandas index
How to turn column header into pandas index

Time:10-18

So my pandas df currently looks something like this:

Detail Person 1 Person 2 Person 3
Name Steve Larry Dave
Age 45 56 67
Hobbie Running Skating Painting

But I want to reshape it to this:

Person Name Age Hobbie
Person 1 Steve 45 Running
Person 2 Larry 56 Skating
Person 3 Dave 67 Painting

Anyone know a way of doing this?

CodePudding user response:

Use:

out = (df.set_index('Detail').T
         .rename_axis('Person')
         .reset_index()
         .rename_axis(columns=None)
      )

Output:

     Person   Name Age    Hobbie
0  Person 1  Steve  45   Running
1  Person 2  Larry  56   Skating
2  Person 3   Dave  67  Painting

CodePudding user response:

All you need to do is transpose the dataframe with df.T and rename the column name using df.rename(). But there is a catch while using df.T it also transpose the index column to row. So we need to work around it. Here is the step by step code:

data.csv:

Detail,Person 1,Person 2,Person 3
Name,Steve,Larry,Dave
Age,45,56,67
Hobbie,Running,Skating,Painting

Reading from file:

import pandas as pd
df = pd.read_csv("data.csv")
print(df)

output:

   Detail Person 1 Person 2  Person 3
0    Name    Steve    Larry      Dave
1     Age       45       56        67
2  Hobbie  Running  Skating  Painting

Changing the column name:

df = df.rename(columns={"Detail":"Person"})
print(df)

output:

   Person Person 1 Person 2  Person 3
0    Name    Steve    Larry      Dave
1     Age       45       56        67
2  Hobbie  Running  Skating  Painting

Transposing with new index column:

df = df.set_index('Person').T
print(df)

output:

Person     Name Age    Hobbie
Person 1  Steve  45   Running
Person 2  Larry  56   Skating
Person 3   Dave  67  Painting

Hope this help!!!! And good luck with your work

  • Related