【问题标题】:Python: Sorting datetime in clustered data using groupby() and apply()Python:使用 groupby() 和 apply() 对聚集数据中的日期时间进行排序
【发布时间】:2021-09-19 12:53:21
【问题描述】:

我想对每个集群的日期时间列进行排序。

    latitude    longitude   cluster datetime          
0   57.723610   11.925191   1       2021-06-13 14:22:11.682
1   57.723614   11.925187   1       2021-06-13 14:22:13.562
2   57.723610   11.925172   1       2021-06-13 14:22:28.635 
3   57.724075   11.923708   2       2021-06-13 14:23:44.905 
4   57.723637   11.925056   2       2021-06-13 14:22:59.336 
5   57.723614   11.925178   3       2021-06-13 14:22:44.170
6   57.723827   11.924635   3       2021-06-13 14:23:14.479 
7   57.723610   11.925191   3       2021-06-13 14:22:04.000
8   57.723866   11.924005   3       2021-06-13 14:23:29.605

为此,我尝试使用 groupby() 和 apply():

# Converting the time column from object to datetime
df["datetime"]= pd.to_datetime(df["datetime"], format="%Y-%m-%d %H:%M:%S.%f")

# Sorting date per cluster
df.groupby("cluster").apply(df.sort_values(by="datetime", inplace=True))    

但是,我收到了错误:

'NoneType' 对象不可调用

我的最终目标是然后将每个集群的行提取到新的 df 中,这些行对应于它们的最早(最旧)和最晚(最近)时间。

【问题讨论】:

    标签: python sorting datetime pandas-groupby apply


    【解决方案1】:

    您需要将function 传递给apply 方法(可调用)。

    你可以在apply中使用lambda函数如下-

    df = df.groupby("cluster").apply(lambda x: x.sort_values(by = 'datetime'))
    

    【讨论】:

      【解决方案2】:

      排序不需要groupby,先按日期时间排序,再按簇排序:

      df.sort_values(["cluster", "datetime"])
      

      但是,如果你想获得每个集群中最早和最新的记录,你可能确实最好在 groupby 中做所有事情:

      (df.groupby("cluster", as_index=False)
         .apply(lambda x: x.sort_values("datetime")
                           .iloc[[0, -1], :]))
      

      【讨论】:

        猜你喜欢
        • 2016-02-01
        • 1970-01-01
        • 2020-03-16
        • 2020-07-24
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        • 2021-12-09
        • 2021-10-06
        相关资源
        最近更新 更多