简体   繁体   中英

Convert row wise data into columns using Pandas

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']})

在此处输入图像描述

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']})

在此处输入图像描述

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.

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM