我认为@DrV是正确的答案,但我准备了一个例子,试图展示如何使用Pandas实现类似的目标:
import numpy
import pandas
import datetime
import time
# Binning delta
delta = datetime.timedelta(hours=1)
# Sample data
sample = [
['2014-08-09 16:30:00', 'label1'],
['2014-08-09 15:30:00', 'label2'],
['2014-08-09 14:30:00', 'label3'],
['2014-08-09 14:00:00', 'label4']
]
# Create dataframe and append UNIX timestamp column
df = pandas.DataFrame(sample)
df.columns = ['Datetime', 'Label']
df['Datetime'] = pandas.to_datetime(df['Datetime'])
df['UnixStamp'] = df['Datetime'].apply(lambda d: time.mktime(d.timetuple()))
df = df.set_index('Datetime')
# Calculate bins
bins = numpy.arange(min(df['UnixStamp']), max(df['UnixStamp']) + delta.seconds, delta.seconds)
# Group columns by datetime bin
def bin_from_tstamp(tstamp):
diffs = [abs(tstamp - bin) for bin in bins]
return bins[diffs.index(min(diffs))]
grouped = df.groupby(df['UnixStamp'].map(
lambda t: datetime.datetime.fromtimestamp(bin_from_tstamp(t))
))
此时
grouped
包含按日期时间段分组的数据集。
以下是打印结果
grouped.groups
(其中键是日期时间箱,值是分组的日期时间):
{
numpy.datetime64('2014-08-09T18:00:00.000000000+0200'): [
Timestamp('2014-08-09 16:30:00')
],
numpy.datetime64('2014-08-09T17:00:00.000000000+0200'): [
Timestamp('2014-08-09 15:30:00')
],
numpy.datetime64('2014-08-09T16:00:00.000000000+0200'): [
Timestamp('2014-08-09 14:30:00'),
Timestamp('2014-08-09 14:00:00'
]
}