【问题标题】:Sort a pandas DataMatrix in ascending order按升序对 pandas DataMatrix 进行排序
【发布时间】:2011-07-30 08:08:24
【问题描述】:

pandas DataFrame 对象有一个sort method,但 pandas DataMatrix 对象没有。

按索引(日期列)以升序对该 DataMatrix 对象进行排序的最佳方法是什么?

>>> 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

结果应该是 DataMatrix,其中 2/8/2011 作为第一个条目,2/16/2011 作为最后一个条目。 Compound_ret 列中的条目应在排序中遵循其日期。所以结果应该是这样的:

>>>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

【问题讨论】:

    标签: python sorting numpy pandas


    【解决方案1】:

    确实在 0.2 和 0.3 之间,我将 sortUp/sortDown 重命名为单个 sort 方法。对此感到抱歉。

    如果可以的话,我绝对建议您跟上 pandas 的前沿 (https://github.com/wesm/pandas)!此外,请考虑将 IPython 用于所有交互式工作 (http://ipython.scipy.org)——我发现制表符补全和对象的轻松自省有助于查找方法和探索文档字符串。

    【讨论】:

      【解决方案2】:

      你试过了吗?至少在我尝试过的 pandas 版本中,DataMatrix 继承自 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         
      

      【讨论】:

      • 感谢回复,见上文。
      • 永远不会失败。就在我发帖的时候,我想通了。无论我使用什么版本,DataMatrix 都有 sortUp() 和 sortDown() 方法。我使用 dir(dataMatrix) 找到了它们。
      • 很奇怪。猜它是一个旧版本;我刚刚从 GitHub 克隆了当前的。
      • 我有0.2版本,新版本是0.3。
      猜你喜欢
      • 2021-05-07
      • 2013-05-30
      • 2019-07-23
      • 1970-01-01
      • 2012-11-29
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多