Como computar média de pandas pd.Timestamp

Problema

Se você tem um array de objetos pd.Timestamp, você não pode computar diretamente a média já que eles não podem ser somados diretamente:

average_timestamp_problem.py
import pandas as pd

# Creating an array of five fixed pd.Timestamp objects
timestamps = [
    pd.Timestamp('2023-01-01 12:00:00'),
    pd.Timestamp('2023-01-02 12:00:00'),
    pd.Timestamp('2023-01-03 12:00:00'),
    pd.Timestamp('2023-01-04 12:00:00'),
    pd.Timestamp('2023-01-05 12:00:00')
]

# FAIL: This will raise a TypeError
average = sum(timestamps) / len(timestamps)

Isso lançará um TypeError:

error.txt
TypeError                                 Traceback (most recent call last)
Cell In[1], line 13
      4 timestamps = [
      5     pd.Timestamp('2023-01-01 12:00:00'),
      6     pd.Timestamp('2023-01-02 12:00:00'),
   (...)
      9     pd.Timestamp('2023-01-05 12:00:00')
     10 ]
     12 # FAIL: This will raise a TypeError
---> 13 average = sum(timestamps) / len(timestamps)

File timestamps.pyx:483, in pandas._libs.tslibs.timestamps._Timestamp.__radd__()

File timestamps.pyx:465, in pandas._libs.tslibs.timestamps._Timestamp.__add__()

TypeError: Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported.  Instead of adding/subtracting `n`, use `n * obj.freq`

Solução

Você pode somar/obter média de ts.value em vez de somar ts diretamente, e após a média, convertê-lo de volta para um timestamp:

average_timestamp_solution.py
average = pd.Timestamp(sum(ts.value for ts in timestamps) / len(timestamps))

Exemplo completo:

average_timestamp_full_example.py
import pandas as pd

# Creating an array of five fixed pd.Timestamp objects
timestamps = [
    pd.Timestamp('2023-01-01 12:00:00'),
    pd.Timestamp('2023-01-02 12:00:00'),
    pd.Timestamp('2023-01-03 12:00:00'),
    pd.Timestamp('2023-01-04 12:00:00'),
    pd.Timestamp('2023-01-05 12:00:00')
]

# Result: Timestamp('2023-01-03 12:00:00')
average = pd.Timestamp(sum(ts.value for ts in timestamps) / len(timestamps))

Check out similar posts by category: Pandas Python