Home > Software engineering >  How to use column containing values as dataframe column headers
How to use column containing values as dataframe column headers

Time:06-29

I have a df:

 Field     Value
  Name      Fred
   Age        69
Gender         M

I want to use the values in 'Field' as the new dataframe column headers to have a df shaped like so:

Name    Age    Gender   
Fred     69         M

Right now I call

df.pivot(columns='Field', values='Value')

but that leaves me with a dataframe of multiple rows containing all NaN values except for one value for that specific row (such as Name).

CodePudding user response:

You can use set_index and transposition (.T):

In [4]: import pandas as pd
   ...:
   ...: df = pd.DataFrame(
   ...:     {
   ...:         "Field": ("Name", "Age", "Gender"),
   ...:         "Value": ("Fred", 69, "M"),
   ...:     }
   ...: )

In [5]: df
Out[5]:
    Field Value
0    Name  Fred
1     Age    69
2  Gender     M

In [6]: df.set_index("Field")
Out[6]:
       Value
Field
Name    Fred
Age       69
Gender     M

In [7]: df.set_index("Field").T
Out[7]:
Field  Name Age Gender
Value  Fred  69      M

To get rid of the index column do:

In [8]: df.set_index("Field").T.reset_index(drop=True).rename_axis(columns="")
Out[8]:
   Name Age Gender
0  Fred  69      M
  • Related