0

I have read several similar questions and their answers but I was still unable to perform the conversion.
This is how my sample dataframe, df looks like:

pd.DataFrame({0: ['Destiantion', 'Switch Location', 'Driver', 'Company'],
1: ['CALGARY', np.nan, 'BALJIT', 'SUPERIOR'],
2: ['CALGARY', np.nan, 'ROBERT', 'APPS'],
3: ['CALGARY', np.nan, 'MARIUS', 'APPS'],
4: ['DELTA', np.nan, np.nan, 'ATC']})

enter image description here

I would like to reformat it such that the values in the column 0, df[0] become the new column headers and the data for the new header columns reside in the same row in the old dataframe.

Expected outcome:

pd.DataFrame({'Destiantion': ['CALGARY', 'CALGARY', 'CALGARY', 'DELTA'],
              'Switch Location': [np.nan, np.nan, np.nan, np.nan],
              'Driver': ['BALJIT', 'ROBERT', 'MARIUS', np.nan],
              'Company': ['SUPERIOR', 'APPS', 'APPS', 'ATC']})

enter image description here

I looked into .pivot() method but I wasn't able to shape the data as I wanted with that and I wasn't sure what the index value was going to be. I can still make this conversion by converting rows into list and extracting headers from the list and creating a new dataframe but I don't feel like it's very "pythonic" and was wondering if there's a better way to do this that I could make use of now and in the future. Any help would be appreciated. Thanks.

1
  • 1
    Look into pandas.transpose() Commented Oct 6, 2019 at 14:01

1 Answer 1

3

Use:

 df=df.set_index(0).T.reset_index(drop=True) 

or if the name of columns are str:

df=df.set_index('0').T.reset_index(drop=True) 
Sign up to request clarification or add additional context in comments.

2 Comments

simpler than mine +1
Add a reset_index(drop=True) to start the index at 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.