【问题标题】:Sort a pandas dataframe based on DateTime field根据 DateTime 字段对 pandas 数据框进行排序
【发布时间】:2016-11-17 12:46:32
【问题描述】:

我正在尝试根据数据类型为 datetime64[ns] 的 DateTime 字段对数据帧进行排序。

我的数据框如下所示:

Name    DateTime1
P38     NaT
P62     2016-07-13 16:03:32.771
P59     2016-06-23 14:23:42.461
P07     NaT
P16     2016-06-23 14:02:06.237
P06     2016-07-13 16:03:52.570
P106    2016-07-13 19:56:22.676

当我使用 DateTime 字段对其进行排序时,

df.sort_values(by='DateTime1',ascending=True)

我没有得到想要的结果。

输出:

Name    DateTime1
P16     2016-06-23 14:02:06.237
P59     2016-06-23 14:23:42.461
P62     2016-07-13 16:03:32.771
P06     2016-07-13 16:03:52.570
P106    2016-07-13 19:56:22.676
P38     NaT
P07     NaT

【问题讨论】:

  • 如果您的问题已解决,请接受解决方案。▲/▼ 箭头下方,答案左上角。

标签: sorting pandas dataframe


【解决方案1】:
  1. 尝试分配回df,否则使用inplace=True,但不要同时使用。见pandas.DataFrame.sort_values
df = df.sort_values(by='DateTime1', ascending=True)
  1. 否则,请尝试pandas.DataFrame.set_index 然后pandas.DataFrame.sort_index
df.set_index('DateTime1', drop=True, append=False, inplace=True, verify_integrity=False)
df = df.sort_index()

【讨论】:

    【解决方案2】:

    我知道这是一个老问题,但 OP 似乎想把 NaN 值放在开头,因为他们发布的输出已经排序。在这种情况下,sort_values 中有一个参数控制放置 NaN 值的位置:na_position

    df = df.sort_values(by='DateTime1', ascending=True, na_position='first')
    

    输出:

       Name               DateTime1
    0   P38                     NaT
    3   P07                     NaT
    4   P16 2016-06-23 14:02:06.237
    2   P59 2016-06-23 14:23:42.461
    1   P62 2016-07-13 16:03:32.771
    5   P06 2016-07-13 16:03:52.570
    6  P106 2016-07-13 19:56:22.676
    

    【讨论】:

      【解决方案3】:

      我尝试了以下两个代码,但都不起作用

      df = df.sort_values(by='DateTime1', ascending=True)
      

      df.set_index('DateTime1', drop=True, append=False, inplace=True, verify_integrity=False)
      
      df = df.sort_index()
      

      我发现工作是将日期时间列转换为索引列,然后按索引排序。所以你的情况是:

      df=df.set_index('DateTime1')       
                                                  
      df=df.sort_index(ascending=False)
      

      【讨论】:

        【解决方案4】:

        对于可能觉得这很有用的其他人。我通过使用 inplace 参数使其工作,如下所示:

        df.sort_values(by='DateTime1', ascending=True, inplace=True)
        

        【讨论】:

          猜你喜欢
          • 2020-02-29
          • 2020-06-18
          • 1970-01-01
          • 2013-06-05
          • 2020-04-23
          • 1970-01-01
          • 1970-01-01
          • 2020-11-18
          • 2012-09-03
          相关资源
          最近更新 更多