pandas - Transposing one column in python dataframe -
i have following:
index id speed _avg_val 245 1 10 30.5 246 1 2 25.1
i want transpose column id , have following:
id (index) speed _avg_val speed_y _avg_val_y 1 10 30.5 2 25.1
i tried use method transposing 1 column in python pandas simplest index possible not work multiple columns.
i think can first remove column index
, add column id
index
, unstack
, sort second level of multiindex in columns sort_index
:
print (df) index id speed _avg_val 0 245 1 10 30.5 1 246 1 2 25.1 df = df.drop('index', axis=1) .set_index('id', append=true) .unstack(0) .sort_index(axis=1, level=1) #remove multiindex columns df.columns = ['_'.join((col[0], str(col[1]))) col in df.columns] print (df) speed_0 _avg_val_0 speed_1 _avg_val_1 id 1 10 30.5 2 25.1
if there more values in id
column, need use cumcount
:
print (df) index id speed _avg_val 0 245 1 10 30.5 1 246 1 2 25.1 2 245 2 5 37.5 3 246 2 28 28.1 4 246 2 27 23.0 df = df.drop('index', axis=1) df['g'] = df.groupby('id').cumcount() df = df.set_index(['id', 'g']).unstack(fill_value=0).sort_index(axis=1, level=1) df.columns = ['_'.join((col[0], str(col[1]))) col in df.columns] print (df) speed_0 _avg_val_0 speed_1 _avg_val_1 speed_2 _avg_val_2 id 1 10 30.5 2 25.1 0 0.0 2 5 37.5 28 28.1 27 23.0
Comments
Post a Comment