开发者

Sort a pandas DataMatrix in ascending order

开发者 https://www.devze.com 2023-02-22 13:12 出处:网络
The pandas DataFrame object has a sort method but pandas DataMatrix开发者_Python百科 object does not.

The pandas DataFrame object has a sort method but pandas DataMatrix开发者_Python百科 object does not.

What is the best way to sort this DataMatrix object by index (the date column) in ascending order?

>>> dm
               compound_ret
2/16/2011 0:00  0.006275682
2/15/2011 0:00  0.003098208
2/14/2011 0:00  0.0055039
2/13/2011 0:00  0.011471506
2/12/2011 0:00  0.011853712
2/11/2011 0:00  0.009558739
2/10/2011 0:00  0.014127912
2/9/2011 0:00   0.02042923
2/8/2011 0:00   0.023308062

The result should be the DataMatrix with 2/8/2011 as the first entry and 2/16/2011 as the last entry. The entries in the compound_ret column should follow their date in the sort. So the result should look something like this:

>>>dm_sorted
                  compound_ret
2/8/2011 0:00    0.023308062
2/9/2011 0:00    0.02042923
2/10/2011 0:00  0.014127912
2/11/2011 0:00  0.009558739
2/12/2011 0:00  0.011853712
2/13/2011 0:00  0.011471506
2/14/2011 0:00  0.0055039
2/15/2011 0:00  0.003098208
2/16/2011 0:00  0.006275682


Indeed between 0.2 and 0.3 I renamed sortUp/sortDown to the single sort methods. Sorry about that.

I definitely recommend keeping up on the bleeding edge of pandas if you can ( https://github.com/wesm/pandas )! Also, consider using IPython for all your interactive work ( http://ipython.scipy.org )-- I find that having tab completion and easy introspection of objects helps a great deal for finding methods and exploring docstrings.


Did you try it? At least in the version of pandas I tried, DataMatrix inherits from DataFrame.

>>> type(dm)
<class 'pandas.core.matrix.DataMatrix'>
>>> dm.sort()
                       compound_ret    
2011-02-08 00:00:00   -0.6986         
2011-02-09 00:00:00    0.1846         
2011-02-10 00:00:00    0.2312         
2011-02-11 00:00:00    1.844          
2011-02-12 00:00:00    0.3662         
2011-02-13 00:00:00    0.1331         
2011-02-14 00:00:00    0.5166         
2011-02-15 00:00:00    1.37           
2011-02-16 00:00:00    0.9346         

>>> dm.sort(ascending=False)                                                    
                       compound_ret    
2011-02-16 00:00:00    0.9346         
2011-02-15 00:00:00    1.37           
2011-02-14 00:00:00    0.5166         
2011-02-13 00:00:00    0.1331         
2011-02-12 00:00:00    0.3662         
2011-02-11 00:00:00    1.844          
2011-02-10 00:00:00    0.2312         
2011-02-09 00:00:00    0.1846         
2011-02-08 00:00:00   -0.6986         
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号