Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use column containing values as dataframe column headers

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading