【问题标题】:Invalid comparison between dtype=datetime64[ns] and Timestampdtype=datetime64[ns] 和 Timestamp 之间的无效比较
【发布时间】:2022-01-02 16:10:40
【问题描述】:

在 Python 中,如果日期低于另一个数据帧的日期,我会尝试删除数据帧的行。但是比较不起作用。

这是我的两个数据框和我尝试比较的结果。 print(MeteoCH.head()) 将导致:

                       TempAvg  TempMin  TempMax
Date                                                                      
2021-11-15 00:00:00      4.4      4.3      4.5     
2021-11-15 01:00:00      4.3      4.3      4.3     
2021-11-15 02:00:00      4.1      4.1      4.2     
2021-11-15 03:00:00      4.0      3.8      4.1    
2021-11-15 04:00:00      3.6      3.4      3.8    

print(PicoLog.head()) 将导致:

                           Temp1   Temp2   Temp3   
Date                                                                        
2021-11-15 18:34:18+01:00  21.268  21.671  21.190     
2021-11-15 18:34:20+01:00  21.266  21.673  21.194     
2021-11-15 18:34:22+01:00  21.270  21.680  21.194     
2021-11-15 18:34:24+01:00  21.263  21.673  21.180    
2021-11-15 18:34:26+01:00  21.262  21.672  21.185

如果我尝试执行以下命令:

MeteoCH.drop(MeteoCH[MeteoCH.index < PicoLog.index.min()], inplace=True)

导致以下错误:

TypeError:dtype=datetime64[ns] 和 Timestamp 之间的比较无效

为什么?如何解决?

我试图以某种方式“转换”它,但它不起作用。

有人可以帮帮我吗?

【问题讨论】:

    标签: python pandas datetime timestamp


    【解决方案1】:

    更简单的是通过大于或等于过滤,反转&lt;,如:

    MeteoCH[MeteoCH.index >= PicoLog.index.min()]
    
    MeteoCH[~(MeteoCH.index < PicoLog.index.min())]
    

    您的解决方案可能是更改过滤MeteoCH.index,但在我看来过于复杂:

    MeteoCH.drop(MeteoCH.index[MeteoCH.index < PicoLog.index.min()], inplace=True)
    

    编辑:

    原来的问题是时区偏移,解决方案是DatetimeIndex.tz_localize:

    PicoLog.index = PicoLog.index.tz_localize(None)
    

    【讨论】:

    • 您好,感谢您的回答,但它不起作用。如果我输入MeteoCH[MeteoCH.index &gt;= PicoLog.index.min()],我还有TypeError: Invalid comparison between dtype=datetime64[ns] and Timestamp
    • @Elfo2285 - 你的熊猫版本是什么?
    • $ pip show pandas Name: pandas Version: 1.3.3
    • 顺便说一句,我应该删除这个固定偏移量。我不知道为什么在我阅读我的 excel 文件时会出现它...
    • @Elfo2285 - 它应该有帮助。试试PicoLog.index = PicoLog.index.tz_localize(None)(就像提到的here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2020-09-04
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多