Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Dataframe help

So I have this dataframe with labels as stock objects. As index, I have 'return' and 'momentum'. I want to sort stocks according to 'momentum' and then find the average 'return' of the top 50 stocks and the bottom 50 stocks then compare the two.

I can totally do it but my code looks really ugly, to the point that it's embarrassing to share as a backtest.
Can any gurus show me how this can be done gracefully?

Thanks

4 responses
count = 50  
df.sort('momentum',inplace=True)  
top_average = df[:count]['return'] .mean()  
bot_average = df[-count:]['return'] .mean()

Wow, thanks. It took me 30 minutes to write the equivalent of those 4 lines :(

Hmm I think that df.sort only works on sorting by label and not index.

put this in front of the other lines

df = df.transpose()