Comment calculer la moyenne d'un pandas pd.Timestamp

Problème

Si vous avez un tableau d’objets pd.Timestamp, vous ne pouvez pas directement calculer la moyenne puisqu’ils ne peuvent pas être sommés directement :

average_timestamp_problem.py
import pandas as pd

# Crée un tableau de cinq objets pd.Timestamp fixes
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')
]

# ÉCHEC : Ceci lèvera une TypeError
average = sum(timestamps) / len(timestamps)

Ceci lèvera une 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 # ÉCHEC : Ceci lèvera une 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`

Solution

Vous pouvez sommer/moyenner ts.value au lieu de sommer ts directement, et après la moyenne, le convertir en timestamp :

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

Exemple complet :

average_timestamp_full_example.py
import pandas as pd

# Crée un tableau de cinq objets pd.Timestamp fixes
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')
]

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

Consultez les articles similaires par catégorie : Pandas Python