0

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

1
  • 1
    this example is so small it's hard to know how the reshape is actually happening. For example, df.set_index('Field').T fits the bar for this example. can you include a couple more rows/columns so we understand what's actually happening in the reshape? I assume you don't just have a single 1:1 mapping between Field and Value? Commented Jun 28, 2022 at 16:35

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

This will set Field/Value as the index column, but I don't want those in the final df... is there a way around this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.