Skip to main content
 首页 » 编程设计

python之在 Pandas 中重新采样

2024年10月24日10zfyouxi

我在另一个线程上问了一个问题 Link .但我得到了一个不完整的答案。也没有人愿意回复。这就是为什么我要提出另一个修改过的问题。让我简单解释一下这个问题,我想对以下数据重新采样:

**` 
Timestamp  L_x   L_y    L_a     R_x     R_y     R_a 
2403950   621.3 461.3   313     623.3   461.8   260 
2403954   622.5 461.3   312     623.3   462.6   260 
2403958   623.1 461.5   311     623.4   464     261 
2403962   623.6 461.7   310     623.7   465.4   261 
2403966   623.8 461.5   309     623.9   466.1   261    
2403970   620.9 461.4   309     623.8   465.9   259 
2403974   621.7 461.1   308     623     464.8   258 
2403978   622.1 461.1   308     621.9   463.9   256 
2403982   622.5 461.5   308     621     463.4   255 
2403986   622.4 462.1   307     620.7   463.3   254 
`** 

table 就这样一直摆下去。所有时间戳都以毫秒为单位。我想将其重新采样到 100L bin 时间。

df = df.resample('100L') 

结果表是: <强> 时间戳 L_x L_y L_a R_x R_y R_a 2403900 621.3 461.3 313 623.3 461.8 260 2404000 622.5 461.3 312 623.3 462.6 260 2404100 623.1 461.5 311 623.4 464 261 2404200 623.6 461.7 310 623.7 465.4 261 2404300 623.8 461.5 309 623.9 466.1 261

但这不是我想要的结果。因为原始表中的第一个时间戳索引是 2403950。所以第一个 bin 时间应该包含从 2403950 到 2404050 但它是 2403900 - 2404000。如下所示: <强> 时间戳 L_x L_y L_a R_x R_y R_a 2403950 …………………… 2404050 …………………… 2404150 …………………… 2404250 …………………… 2404350 …………………… 该列的其余部分是原始表的值的平均值。 因此,有人建议我必须计算偏移量。在我的例子中是 50 毫秒。并执行以下操作:

df.resample('100L', loffset='50L') 

偏移量只会将标签向前移动 50 毫秒,但不会改变平均值。它仍在计算 2403900 到 2404000 之间的值的平均值,例如第一个 bin 时间,而不是 2403950 到 2404050 之间的值。

谢谢你的帮助

请您参考如下方法:

你正在寻找 base kwarg。

base : int, default 0
For frequencies that evenly subdivide 1 day, the “origin” of the aggregated intervals. For example, for ‘5min’ frequency, base could range from 0 through 4. Defaults to 0


在你的情况下,它看起来像你想要的:

df.resample('100L', base=50) 

注意:没有 DatetimeIndex/PeriodIndex/TimedeltaIndex 的重采样会在最近的 pandas 中引发错误,因此您应该在执行此操作之前转换为 DatetimeIndex。