在 google colab 最新更新之后,在 dtype datetime64 上使用查询方法时,我收到未来警告:
“不推荐使用 dtype=datetime64[ns] 和可转换值(例如字符串)的 'isin' 行为。在未来版本中,isin 不会将这些视为匹配。在调用 isin 之前显式转换为适当的 dtype。 ”
import numpy as np
import pandas as pd
df = pd.DataFrame({'some_dates' :[pd.Timestamp('2024-09-30 00:00:00'),
pd.Timestamp('2024-09-23 00:00:00')]})
print(df.dtypes)
---output :
some_dates datetime64[ns]
dtype: object
df.query("some_dates in [('2024-09-30 00:00:00')]")
---output :
<ipython-input-53-09d8c5b6f74b>:1: FutureWarning: The behavior of 'isin' with dtype=datetime64[ns] and castable values (e.g. strings) is deprecated. In a future version, these will not be considered matching by isin. Explicitly cast to the appropriate dtype before calling isin instead.
df.query("some_dates in [('2024-09-30 00:00:00')]")
some_dates
0 2024-09-30
使用 isin 消除警告:
df['some_dates'].isin([np.datetime64('2024-09-30 00:00:00')])
---output :
some_dates
0 True
1 False
dtype: bool
但我很难将其应用到查询方法中:
df.query("some_dates in [np.datetime64('2024-09-30 00:00:00')]")
---output :
UndefinedVariableError: name 'np' is not defined
编辑:刚刚发现传递 @pd.Timestamp(date) 有效:
df.query("some_dates in [@pd.Timestamp('2024-09-30 00:00:00')]")
---output :
some_dates
0 2024-09-30
但是@np.datetime64 没有: ''' df.query("some_dates in [@np.datetime64('2024-09-30 00:00:00')]") - -输出 : 类型错误:“numpy._ArrayFunctionDispatcher”和“int”的实例之间不支持“>” '''
请参阅上面我的编辑,使用@pd.Timestamp()