gpt4 book ai didi

python - 带有 numpy.maximum 的 Pandas Datetimeindex 给出错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:31 25 4
gpt4 key购买 nike

我遇到的错误可能是 pandas(Windows 上的 v.0.22,Python 版本 3.6.3)中的错误,或者更确切地说是它与 NumPy 的交互(v.1.14)中的错误,但我想知道我是否缺少更深刻的东西。

这里是问题所在:如果我有两个相同长度的 Datetimeindex 对象,并且我在它们之间使用了 np.maximum,则输出符合预期:

import pandas as pd
import numpy as np
v1 = pd.DatetimeIndex(['2016-01-01', '2018-01-02', '2018-01-03'])
v2 = pd.DatetimeIndex(['2017-01-01', '2017-01-02', '2019-01-03'])
np.maximum(v1, v2)

返回元素最大值:

DatetimeIndex(['2017-01-01', '2018-01-02', '2019-01-03'], dtype='datetime64[ns]', freq=None)

但是,如果我尝试只使用两者中的一个元素,则会出现错误:

np.maximum(v1, v2[0])

pandas_libs\tslib.pyx in pandas._libs.tslib._Timestamp.richcmp()

TypeError: Cannot compare type 'Timestamp' with type 'int'

有两个可行的解决方法,但都很难编写,要么使用切片,要么显式转换为 pydatetime:

np.maximum(v1, v2[:1])

DatetimeIndex(['2017-01-01', '2018-01-02', '2018-01-03'], dtype='datetime64[ns]', freq=None)

或:

v1.to_pydatetime() - v2[0].to_pydatetime()

array([datetime.datetime(2017, 1, 1, 0, 0), datetime.datetime(2018, 1, 2, 0, 0), datetime.datetime(2018, 1, 3, 0, 0)], dtype=object)

第一个解决方法实际上很奇怪,因为 v2 - v1[0] 工作正常,而 v2 - v1[:1] 给出了一个错误(而不是这一次是预期的,因为两个结果时间序列具有未对齐的索引)。

最佳答案

一种解决方案是转换为 pd.Series,然后使用 pd.Series.clip :

pd.Series(v1).clip(v2[0])

# 0 2017-01-01
# 1 2018-01-02
# 2 2018-01-03
# dtype: datetime64[ns]

关于python - 带有 numpy.maximum 的 Pandas Datetimeindex 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48744607/

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