如何在Pyspark中使用滑动窗口对时间序列数据进行数据转换

Bin*_*Bin 10 python time-series apache-spark pyspark

我试图基于时间序列数据的滑动窗口提取功能.在Scala中,似乎有一个sliding基于这篇文章文档的函数

import org.apache.spark.mllib.rdd.RDDFunctions._

sc.parallelize(1 to 100, 10)
  .sliding(3)
  .map(curSlice => (curSlice.sum / curSlice.size))
  .collect()
Run Code Online (Sandbox Code Playgroud)

我的问题是PySpark中有类似的功能吗?或者,如果没有这样的功能,我们如何实现类似的滑动窗口转换呢?

zer*_*323 12

据我所知,sliding函数不能从Python获得,并且SlidingRDD是私有类,无法在外部访问MLlib.

如果您sliding在现有的RDD 上使用,您可以创建这样的穷人sliding:

def sliding(rdd, n):
    assert n > 0
    def gen_window(xi, n):
        x, i = xi
        return [(i - offset, (i, x)) for offset in xrange(n)]

    return (
        rdd.
        zipWithIndex(). # Add index
        flatMap(lambda xi: gen_window(xi, n)). # Generate pairs with offset
        groupByKey(). # Group to create windows
        # Sort values to ensure order inside window and drop indices
        mapValues(lambda vals: [x for (i, x) in sorted(vals)]).
        sortByKey(). # Sort to makes sure we keep original order
        values(). # Get values
        filter(lambda x: len(x) == n)) # Drop beginning and end
Run Code Online (Sandbox Code Playgroud)

或者你也可以尝试这样的东西(只需一点帮助toolz)

from toolz.itertoolz import sliding_window, concat

def sliding2(rdd, n):
    assert n > 1

    def get_last_el(i, iter):
        """Return last n - 1 elements from the partition"""
        return  [(i, [x for x in iter][(-n + 1):])]

    def slide(i, iter):
        """Prepend previous items and return sliding window"""
        return sliding_window(n, concat([last_items.value[i - 1], iter]))

    def clean_last_items(last_items):
        """Adjust for empty or to small partitions"""
        clean = {-1: [None] * (n - 1)}
        for i in range(rdd.getNumPartitions()):
            clean[i] = (clean[i - 1] + list(last_items[i]))[(-n + 1):]
        return {k: tuple(v) for k, v in clean.items()}

    last_items = sc.broadcast(clean_last_items(
        rdd.mapPartitionsWithIndex(get_last_el).collectAsMap()))

    return rdd.mapPartitionsWithIndex(slide)
Run Code Online (Sandbox Code Playgroud)


Sha*_*ran 5

为了补充venuktan的答案,以下是如何使用 Spark SQL 创建基于时间的滑动窗口并保留窗口的完整内容,而不是对其进行聚合。在我将时间序列数据预处理到滑动窗口中以输入 Spark ML 的用例中需要这样做。

这种方法的一个限制是我们假设您希望随着时间的推移采用滑动窗口。

首先,您可以创建 Spark DataFrame,例如通过读取 CSV 文件:

df = spark.read.csv('foo.csv')
Run Code Online (Sandbox Code Playgroud)

我们假设您的 CSV 文件有两列:其中一列是 unix 时间戳,另一列是您要从中提取滑动窗口的列。

from pyspark.sql import functions as f

window_duration = '1000 millisecond'
slide_duration = '500 millisecond'

df.withColumn("_c0", f.from_unixtime(f.col("_c0"))) \
    .groupBy(f.window("_c0", window_duration, slide_duration)) \
    .agg(f.collect_list(f.array('_c1'))) \
    .withColumnRenamed('collect_list(array(_c1))', 'sliding_window')
Run Code Online (Sandbox Code Playgroud)

额外奖励:要将此数组列转换为 Spark ML 所需的 DenseVector 格式,请参阅此处的 UDF 方法

额外奖励:要取消嵌套结果列,以便滑动窗口的每个元素都有自己的列,请在此处尝试此方法

我希望这有帮助,如果我可以澄清任何事情,请告诉我。