【问题标题】:Python: Pandas dataframe re-arrange rows based on last three digits of Integer in ColumnPython:熊猫数据框根据列中整数的最后三位重新排列行
【发布时间】:2018-10-17 18:06:47
【问题描述】:

我有以下数据框:

YearMonth   Total Cost
2015009     $11,209,041 
2015010     $20,581,043 
2015011     $37,079,415 
2015012     $36,831,335 
2016008     $57,428,630 
2016009     $66,754,405 
2016010     $45,021,707 
2016011     $34,783,970 
2016012     $66,215,044 

YearMonth 是一个 int64 列。 YearMonth 中的一个值(例如 2015009)代表 2015 年 9 月。我想重新排序行,以便如果最后 3 位数字相同,那么我希望这些行按年份排序显示在彼此的顶部。

下面是我想要的输出:

YearMonth   Total Cost
2015009     $11,209,041 
2016009     $66,754,405     
2015010     $20,581,043 
2016010     $45,021,707    
2015011     $37,079,415 
2016011     $34,783,970   
2015012     $36,831,335 
2016012     $66,215,044
2016008     $57,428,630

我已经搜索了谷歌,试图找到如何做到这一点,但无济于事。

【问题讨论】:

    标签: python sorting search integer


    【解决方案1】:

    一种将 int 列转换为字符串并将字符串访问与索引结合使用的方法。

    df.assign(sortkey=df.YearMonth.astype(str).str[-3:])\
      .sort_values('sortkey')\
      .drop('sortkey', axis=1)
    

    输出:

       YearMonth   Total Cost
    4    2016008  $57,428,630
    0    2015009  $11,209,041
    5    2016009  $66,754,405
    1    2015010  $20,581,043
    6    2016010  $45,021,707
    2    2015011  $37,079,415
    7    2016011  $34,783,970
    3    2015012  $36,831,335
    8    2016012  $66,215,044
    

    【讨论】:

      【解决方案2】:
      df['YearMonth'] = pd.to_datetime(df['YearMonth'],format = '%Y0%m')
      df['Year'] = df['YearMonth'].dt.year
      df['Month'] = df['YearMonth'].dt.month
      df.sort_values(['Month','Year'])
      
              YearMonth   Total   Year    Month
      8   2016-08-01  $57,428,630 2016    8
      0   2015-09-01  $11,209,041 2015    9
      1   2016-09-01  $66,754,405 2016    9
      2   2015-10-01  $20,581,043 2015    10
      3   2016-10-01  $45,021,707 2016    10
      4   2015-11-01  $37,079,415 2015    11
      5   2016-11-01  $34,783,970 2016    11
      6   2015-12-01  $36,831,335 2015    12
      7   2016-12-01  $66,215,044 2016    12
      

      一种做法。可能有一种更快的方法,步骤更少,不涉及将YearMonth 转换为日期时间,但如果您有日期,使用它更有意义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-16
        • 2022-06-13
        • 2012-06-19
        相关资源
        最近更新 更多