您可以使用以下方式填写您错过的时间pandas.DataFrame.resample
。需要注意的是数据框需要有一个pandas.DateTimeIndex
。在您的情况下,时间可能会存储为自纪元以来以秒为单位的浮点数,并且需要在重新采样之前进行转换。这是一个将执行该操作的函数。
Code:
import datetime as dt
import pandas as pd
def resample(dataframe, time_column, sample_period):
# make a copy of the dataframe
dataframe = dataframe.copy()
# convert epoch times to datetime
dataframe.time = dataframe.time.apply(
lambda ts: dt.datetime.fromtimestamp(ts))
# make the datetimes into an index
dataframe.set_index(time_column, inplace=True)
# resample to desired period
dataframe = dataframe.resample(sample_period).asfreq().reset_index()
# convert datetimes back to epoch
epoch = dt.datetime.fromtimestamp(0)
dataframe.time = dataframe.time.apply(
lambda ts: (ts - epoch).total_seconds())
return dataframe
测试代码:
values = [
(1488771900.10, 'a'),
(1488771900.20, 'b'),
(1488771900.30, 'c'),
(1488771900.60, 'f'),
]
columns = ['time', 'value']
df = pd.DataFrame(values, columns=columns)
print(df)
new_df = resample(df, 'time', '100ms')
print(new_df)
Results:
time value
0 1.488772e+09 a
1 1.488772e+09 b
2 1.488772e+09 c
3 1.488772e+09 f
time value
0 1.488772e+09 a
1 1.488772e+09 b
2 1.488772e+09 c
3 1.488772e+09 NaN
4 1.488772e+09 NaN
5 1.488772e+09 f