Problema
Si tienes un array de objetos pd.Timestamp, no puedes calcular directamente el promedio ya que no pueden ser sumados directamente:
average_timestamp_problem.py
import pandas as pd
# Crear un array de cinco objetos pd.Timestamp fijos
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: Esto lanzará un TypeError
average = sum(timestamps) / len(timestamps)Esto lanzará un 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: Esto lanzará un 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`Solución
Puedes sumar/promediar ts.value en lugar de sumar ts directamente, y después del promediado, convertirlo de vuelta a un timestamp:
average_timestamp_solution.py
average = pd.Timestamp(sum(ts.value for ts in timestamps) / len(timestamps))Ejemplo completo:
average_timestamp_full_example.py
import pandas as pd
# Crear un array de cinco objetos pd.Timestamp fijos
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))Si este artículo te ha ayudado, considera invitarme a un café o hacer una donación vía PayPal para apoyar la investigación y publicación de nuevos artículos en TechOverflow