0

e.g.

Before:

df = pd.DataFrame({'TT':['AA','AA','AA','BB','BB','BB','CC','CC','CC'],'value':[1,2,3,4,5,6,7,8,9]})

Wanted like below:

df_new = pd.DataFrame({'AA':[1,2,3],'BB':[4,5,6],'CC':[7,8,9]})

Here is my code:

import pandas as pd
df = pd.DataFrame({'TT':['AA','AA','AA','BB','BB','BB','CC','CC','CC'],'value':[1,3,3,4,5,6,8,8,9]})
cols= ['AA','BB','CC']
parts = []
for col in cols:   
    part = pd.DataFrame(df.loc[(df['TT']==col)].iloc[:,1])
    part =part.reset_index(drop=True)
    parts.append(part)
    df_new=pd.concat(parts,axis=1,ignore_index=True)
df_new.columns=[cols]    

I wonder is there any efficient way to achieve my requirement.

AskNature
  • 85
  • 1
  • 7

0 Answers0