按时间顺序更改频率

时间:2019-01-25 12:51:05

标签: python pandas

我有一个布尔变量的数据框,由时间戳标识。时间戳是不规则的,我希望填补空白。我知道所需的频率是3毫秒。

到目前为止,我可以执行以下操作:

df = pd.read_csv(path, sep= ';')
df['timestamp'] = pd.to_datetime(df ['timestamp'], errors='raise',infer_datetime_format = True)
df = df.sort(['timestamp'])
df = df.set_index('timestamp')
df.reindex(pd.period_range(df.index[0], df.index[-1], freq='ms'))     
df = df.fillna(method = 'ffill')

因此,我使用ms间隔重新索引并填充缺失值(这正是我的情况:所有变量均为布尔值,因此在每时每刻,当前状态都是数据中的最后一个出现)。

如何每3毫秒重新采样一次?

EDIT:似乎DataFrame.resample也可以用于上采样。关于如何在我的情况下使用它的任何建议?我似乎不知道它是如何工作的。

2 个答案:

答案 0 :(得分:2)

使用DataFrame.asfreq

df = pd.DataFrame({
    'timestamp': pd.to_datetime(['2015-02-01 15:14:11.30',
                                 '2015-02-01 15:14:11.36',
                                 '2015-02-01 15:14:11.39']),
    'B': [7,10,3]
})
print (df)
                timestamp   B
0 2015-02-01 15:14:11.300   7
1 2015-02-01 15:14:11.360  10
2 2015-02-01 15:14:11.390   3

df = df.set_index('timestamp').asfreq('3ms', method='ffill')

print (df)
                          B
timestamp                  
2015-02-01 15:14:11.300   7
2015-02-01 15:14:11.303   7
2015-02-01 15:14:11.306   7
2015-02-01 15:14:11.309   7
2015-02-01 15:14:11.312   7
2015-02-01 15:14:11.315   7
2015-02-01 15:14:11.318   7
2015-02-01 15:14:11.321   7
2015-02-01 15:14:11.324   7
2015-02-01 15:14:11.327   7
2015-02-01 15:14:11.330   7
2015-02-01 15:14:11.333   7
2015-02-01 15:14:11.336   7
2015-02-01 15:14:11.339   7
2015-02-01 15:14:11.342   7
2015-02-01 15:14:11.345   7
2015-02-01 15:14:11.348   7
2015-02-01 15:14:11.351   7
2015-02-01 15:14:11.354   7
2015-02-01 15:14:11.357   7
2015-02-01 15:14:11.360  10
2015-02-01 15:14:11.363  10
2015-02-01 15:14:11.366  10
2015-02-01 15:14:11.369  10
2015-02-01 15:14:11.372  10
2015-02-01 15:14:11.375  10
2015-02-01 15:14:11.378  10
2015-02-01 15:14:11.381  10
2015-02-01 15:14:11.384  10
2015-02-01 15:14:11.387  10
2015-02-01 15:14:11.390   3

答案 1 :(得分:1)

如果您的时间戳记在索引中:

sys.stdout

编辑:

性能基准

df = df.resample('3ms').ffill()

结果:

import time
import pandas as pd


dd = {'dt': ['2018-01-01 00:00:00', '2018-01-01 01:12:59'], 'v':[1,1]}

df = pd.DataFrame(data=dd)
df['dt'] = pd.to_datetime(df['dt'])
df = df.set_index('dt')

start = time.time()
df = df.resample('3ms').ffill()
print(time.time() - start)


df = pd.DataFrame(data=dd)
df['dt'] = pd.to_datetime(df['dt'])
df = df.set_index('dt')

start = time.time()
df = df.asfreq('3ms', method='ffill')
print(time.time() - start)

print(df.shape)