我正在尝试在pandas.DataFrames
字段上加入两个datetime64[ns, UTC]
,但是失败了,这对我来说并不直观,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
字段不是int64
。 documentation 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
之前,我不能:这不是我的代码;)
答案 0 :(得分:1)
有时索引与日期时间索引的结合不起作用。我真的不知道为什么,但是对我有用的是使用合并,然后按如下所示显式转换两个合并列:
df['Time'] = pd.to_datetime(df['Time'], utc = True)
在为我工作的两个列中都这样做之后。您也可以在使用联接操作之前尝试此操作,并使用上述过程再次转换两个索引。
可以在这里找到更正确的方法:Pandas timezone-aware timestamp to naive timestamp conversion