Skip to main content
 首页 » 编程设计

python之如何从 Pandas 的第一个元素开始重新采样

2025年05月04日19findumars

我正在对下表/数据进行重采样:

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 就这样一直摆下去。 时间戳以毫秒为单位。我执行了以下操作以将其重新采样为 100 毫秒的 bin 时间:

  1. 我将时间戳索引更改为日期时间格式

    df.index = pd.to_datetime((df.index.values*1e6).astype(int))

  2. 我在 100 毫秒内对其重新采样:

    df = df.resample('100L')

生成的重采样数据如下所示:

Timestamp  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 

我们可以看到第一个bin时间是2403900,比原表的第一个时间戳索引晚了50毫秒。但我希望 bin 时间从原始表的第一个时间戳索引开始,即 2403950。如下所示:

Timestamp  L_x   L_y    L_a     R_x     R_y     R_a 
2403950   621.3 461.3   313     623.3   461.8   260 
2404050   622.5 461.3   312     623.3   462.6   260 
2404150   623.1 461.5   311     623.4   464     261 
2404250   623.6 461.7   310     623.7   465.4   261 
2404350   623.8 461.5   309     623.9   466.1   261 

请您参考如下方法:

您可以指定一个偏移量:

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

更新

当然你总是可以计算偏移量:

offset = df.index[0] % 100 
df.index = pd.to_datetime((df.index.values*1e6).astype(int)) 
df.resample('100L', loffset='{}L'.format(offset))