【发布时间】:2021-12-20 07:24:53
【问题描述】:
有人知道如何计算索引时间戳的时间增量吗?
import pandas as pd
import numpy as np
# simulate some data
# ===================================
np.random.seed(0)
dt_rng = pd.date_range('2015-03-02 00:00:00', '2015-07-19 23:00:00', freq='T')
dt_idx = pd.DatetimeIndex(np.random.choice(dt_rng, size=2000, replace=False))
df = pd.DataFrame(np.random.randn(2000), index=dt_idx, columns=['col']).sort_index()
df
我在使用df['elapsed_time'] = pd.TimedeltaIndex(df) 时是否在使用with this?
这将引发错误:
ValueError: Wrong number of items passed 2000, placement implies 1
【问题讨论】:
-
你不能传递一个DataFrame。只有一个系列。
df['elapsed_time'] = pd.TimedeltaIndex(df.index) -
有点不清楚您要做什么,因为这只会占用底层的 ns 日期时间并将其 强制 转换为时间增量。它不会进行任何 timedelta 比较。
-
您似乎在寻找
df['elapsed_time'] = df.index.to_series().diff()Difference pandas.DateTimeIndex without a frequency