Jas*_*pel 8 python python-3.x pandas
我试图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
Run Code Online (Sandbox Code Playgroud)
显然该date字段不是int64. 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
Run Code Online (Sandbox Code Playgroud)
在您建议我遵循友好说明并使用之前pd.concat,我不能:这不是我的代码;)
inn*_*neb 15
有时索引连接与日期时间索引不起作用。我真的不知道为什么,但对我有用的是使用合并,然后在显式转换两个合并列之前,如下所示:
df['Time'] = pd.to_datetime(df['Time'], utc = True)
Run Code Online (Sandbox Code Playgroud)
在我为对我有用的两列这样做之后。您也可以在使用连接操作之前尝试此操作,并使用上述使用的过程再次转换两个索引。
更正确的方法可以在这里找到:Pandas timezone-aware timestamp to naive timestamp conversion
| 归档时间: |
|
| 查看次数: |
8676 次 |
| 最近记录: |