Home > Software engineering >  Convert column to dataframe column geaders
Convert column to dataframe column geaders

Time:12-15

I have the following pandas dataframe

Input DataFrame

I would like it to be converted to a pandas dataframe with one row. Is there a simple way to do it. I tried pivot but was getting weird results. Output Dataframe

CodePudding user response:

You can pivot, swap the level of columns names, shift values up to fill NaN values and flatten column names:

out = df.pivot(columns='Study Identification').swaplevel(0,1,axis=1).apply(lambda x: pd.Series(x.dropna().values)).fillna('')
out.columns = s.columns.map(''.join)

CodePudding user response:

So in your case reshape the df with unstack

s = df.set_index('A',append=True).unstack(level=1).swaplevel(0,1,axis=1)
s.columns = s.columns.map(''.join)
  • Related