gpt4 book ai didi

python - 使用 pandas.join 加入 datetime64[ns, UTC] 失败

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:35 30 4
gpt4 key购买 nike

我正在尝试在 datetime64[ns, UTC] 字段上加入两个 pandas.DataFrames,但它因 ValueError 而失败(如下所述)这对我来说并不直观。考虑这个例子:

>>> import pandas as pd
>>> import numpy as np
>>>
>>> s_1 = pd.Series(np.random.randn(2,), index=['1981-12-10', '1984-09-14'])
>>> s_1.index = pd.to_datetime(s_1.index, utc=True)
>>> df_1 = pd.DataFrame(s_1, columns=['s_1']).assign(date=s_1.index)
>>> df_1.dtypes
s_1 float64
date datetime64[ns, UTC]
dtype: object
>>>
>>> d = {
... 'v': np.random.randn(2,),
... 'close': ['1981-12-10', '1984-09-14']
>>> }
>>> df_2 = pd.DataFrame(data=d)
>>> df_2.close = pd.to_datetime(df_2.close, utc=True)
>>> df_2['date'] = df_2.close.apply(lambda x: x.replace(hour=0, minute=0, second=0))
>>> df_2.dtypes
v float64
close datetime64[ns, UTC]
date datetime64[ns, UTC]
dtype: object
>>>
>>> df_1.join(df_2, on='date', lsuffix='_')
[...stacktrace ommitted for brevity...]
ValueError: You are trying to merge on datetime64[ns, UTC] and int64 columns. If you wish to proceed you should use pd.concat

显然 date 字段不是 int64documentation for join说“索引应该类似于这一列中的其中一列。”所以我将 df_2 的索引设置为 date 字段并再次尝试:

>>> df_2.set_index('date', drop=False, inplace=True)
>>> df_1.dtypes
s_1 float64
date datetime64[ns, UTC]
dtype: object
>>> df_1.index
DatetimeIndex(['1981-12-10', '1984-09-14'], dtype='datetime64[ns, UTC]', freq=None)
>>>
>>> df_2.dtypes
v float64
close datetime64[ns, UTC]
date datetime64[ns, UTC]
dtype: object
>>> df_2.index
DatetimeIndex(['1981-12-10', '1984-09-14'], dtype='datetime64[ns, UTC]', name='date', freq=None)
>>>
>>> df_1.join(df_2, on='date', lsuffix='_')
[...stacktrace ommitted for brevity...]
ValueError: You are trying to merge on datetime64[ns, UTC] and datetime64[ns] columns. If you wish to proceed you should use pd.concat

在你建议我按照友好的说明使用 pd.concat 之前,我不能:这不是我的代码;)

最佳答案

有时,日期时间索引的索引连接不起作用。我真的不知道为什么,但对我有用的是使用 merge 和在显式转换两个合并列之前,如下所示:

df['Time'] = pd.to_datetime(df['Time'], utc = True)

在我对两个对我有用的列执行此操作之后。您也可以在使用连接操作之前尝试此操作,并使用上面使用的过程再次转换两个索引。

可以在这里找到更正确的方法:Pandas timezone-aware timestamp to naive timestamp conversion

关于python - 使用 pandas.join 加入 datetime64[ns, UTC] 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452135/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com