如何获得熊猫日期时间系列的最小值和另一个日期时间系列的(常数)最大值?

时间:2021-01-21 22:53:47

标签: python pandas numpy datetime

假设我有两个日期时间序列:

foo = pd.to_datetime(pd.Series([
    '2020-01-01 12:00:00',
    '2020-02-02 23:12:00'
]))

bar = pd.to_datetime(pd.Series([
    '2020-01-20 01:02:03',
    '2020-01-30 03:02:01'
]))

两者都是 datetime64[ns] 类型:

>>> foo
0   2020-01-01 12:00:00
1   2020-02-02 23:12:00
dtype: datetime64[ns]
>>> bar
0   2020-01-20 01:02:03
1   2020-01-30 03:02:01
dtype: datetime64[ns]

对于 foo 中的每个元素,我想得到以下的最小值:

  1. 来自 foo 的值
  2. bar 的(常数)最大值

但这会产生一个 TypeError

>>> np.minimum(foo, bar.max())
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
...
TypeError: '<=' not supported between instances of 'int' and 'Timestamp'

如果我自己做 Series 就行了:

>>> np.minimum(foo, bar)
0   2020-01-01 12:00:00
1   2020-01-30 03:02:01
dtype: datetime64[ns]

bar.max() 出于某种原因返回 Timestamp,而不是 datetime64,但即使使用显式 python datetime 对象也不起作用。为什么 numpy 将 foo 视为 int?有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:3)

使用 pandas.Series.where

foo.where(foo < bar.max(), bar.max())

如果条件 (foobar.max()

)

答案 1 :(得分:0)

怎么样

>>> barmax = bar.max()
>>> barmax
Timestamp('2020-01-30 03:02:01')
>>> foo.map(lambda x: np.minimum(x, barmax))
0   2020-01-01 12:00:00
1   2020-01-30 03:02:01
dtype: datetime64[ns]
>>> 
相关问题