【问题标题】:Deleting first instance of date in dataframe value Python删除数据框值Python中的第一个日期实例
【发布时间】:2023-04-07 03:58:01
【问题描述】:

我有一个如下所示的数据框:

Publication Date        Date              Value
2018-01-01              2018-01-01        2
2018-01-01              2018-01-02        13
2018-01-01              2018-01-03        14
2018-01-01              2018-01-04        12
2018-01-02              2018-01-02        1.5
2018-01-02              2018-01-03        14
2018-01-02              2018-01-04        15
2018-01-02              2018-01-05        15.5
2018-01-03              2018-01-03        1.8
2018-01-03              2018-01-04        13
2018-01-03              2018-01-05        17
2018-01-03              2018-01-06        15
.
.

我想删除Publication Date 更改的每一行数据,因为每次迭代都有非常小的值。输出如下所示:

Publication Date        Date              Value
2018-01-01              2018-01-02        13
2018-01-01              2018-01-03        14
2018-01-01              2018-01-04        12
2018-01-02              2018-01-03        14
2018-01-02              2018-01-04        15
2018-01-02              2018-01-05        15.5
2018-01-03              2018-01-04        13
2018-01-03              2018-01-05        17
2018-01-03              2018-01-06        15
.
.

数据基本上采用这种格式,但包括未显示的额外列(即:Date 切换每个Publication Date 的日期+1)。

最好的方法是什么?

【问题讨论】:

    标签: python python-3.x pandas dataframe pandas-groupby


    【解决方案1】:

    您可以将布尔索引与 shift 结合使用

    df[df['Publication Date'] == df['Publication Date'].shift()]
    
    
        Publication Date    Date    Value
    1   2018-01-01  2018-01-02  13.0
    2   2018-01-01  2018-01-03  14.0
    3   2018-01-01  2018-01-04  12.0
    5   2018-01-02  2018-01-03  14.0
    6   2018-01-02  2018-01-04  15.0
    7   2018-01-02  2018-01-05  15.5
    9   2018-01-03  2018-01-04  13.0
    10  2018-01-03  2018-01-05  17.0
    11  2018-01-03  2018-01-06  15.0
    

    【讨论】:

      【解决方案2】:

      使用duplicated

      res = df[df.duplicated(subset=['PublicationDate'])]
      

      或者,更概括地说,使用cumcounttailgroupby

      res = df[df.groupby('PublicationDate').cumcount() > 0]
      
      res = df.groupby('PublicationDate').apply(lambda x: x.tail(len(x)-1))\
              .reset_index(drop=True)
      
      print(res)
      
        PublicationDate        Date  Value
      0      2018-01-01  2018-01-02   13.0
      1      2018-01-01  2018-01-03   14.0
      2      2018-01-01  2018-01-04   12.0
      3      2018-01-02  2018-01-03   14.0
      4      2018-01-02  2018-01-04   15.0
      5      2018-01-02  2018-01-05   15.5
      6      2018-01-03  2018-01-04   13.0
      7      2018-01-03  2018-01-05   17.0
      8      2018-01-03  2018-01-06   15.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2018-09-23
        • 2018-03-02
        • 1970-01-01
        相关资源
        最近更新 更多