在Python中按时间序列分类对项目进行分组

时间:2014-08-09 13:20:34

标签: python binning

我的数据看起来像:

[[datetime1, label1],
 [datetime2, label2],
 [datetime3, label3]]

标签是字符串。我有一个binning参数(delta),它是一个datetime.timedelta。

我想做的事情:

  1. 提出一组日期时间箱,以三角形间隔。换句话说,在下面,datetimebin2 - datetimebin1 = datetimebin3 - datetimebin2 = delta。
  2. 将标签分成这些箱子。
  3. 所以我最终会得到类似的东西:

    [[datetimebin1, [label1, label2],
     [datetimebin2, []],
     [datetimebin3, []],
     [datetimebin4, [label3]]
    

    我已经指出了大熊猫,但我找不到我想要的东西。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

这些方面应该做的事情:

# data: a lists of lists (length 2) of measurements
# res: resulting list of lists
# delta: time delta

# output list (will be a list of lists, as in the question

res = []
# end of first bin:
binstart = data[0][0]
res.append([binstart, []])

# iterate through the data item
for d in data:
    # if the data item belongs to this bin, append it into the bin
    if d[0] < binstart + delta:
        res[-1][1].append(d[1])
        continue

    # otherwise, create new empty bins until this data fits into a bin
    binstart += delta
    while d[0] > binstart + delta:
        res.append([binstart, [])
        binstart += delta

    # create a bin with the data
    res.append([binstart, [d[1]]])

答案 1 :(得分:2)

我认为@ 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'
    ]
}