1

Input Dataframe:

enter image description here

I am trying to pivot my df by sorting Time Column in column wise
my output df:
enter image description here

Pivoting df wont give Time in sorted order. Is there any alternate way to do ?

1

1 Answer 1

1

You need reindex by unique values of column Loc_Time with sort_values by column Time, because pivot by default sorting:

df1 = df.pivot('Group','Loc_Time','Value')
df1 = df1.reindex(columns=df.sort_values('Time')['Loc_Time'].unique())
print (df1)
Loc_Time  loc1_Week1  loc2_Week1  loc3_Week1  loc1_Week2  loc2_Week2  \
Group                                                                  
prod1             10          12          14          11          13   
prod2             20          22          24          21          23   

Loc_Time  loc3_Week2  
Group                 
prod1             15  
prod2             25  

Detail:

print (df.sort_values('Time')['Loc_Time'].unique())

['loc1_Week1' 'loc2_Week1' 'loc3_Week1' 'loc1_Week2' 'loc2_Week2'
 'loc3_Week2']
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, @jezrael but my desired output is lill different from yours. I need Time column to be sorted.

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.