vaex:将列移动 n 步

vaex: shift column by n steps

我正在为监督学习任务准备一个大型多变量时间序列数据集,我想创建我的输入特征的时移版本,以便我的模型也可以从过去的值中推断出来。 pandas 中有一个 shift(n) 命令,可让您将列移动 n 行。 vaex中有类似的东西吗?

我在 vaex 文档中找不到任何可比较的内容。

不,我们还不支持它 (https://github.com/vaexio/vaex/issues/660). Because vaex is extensible (see http://docs.vaex.io/en/latest/tutorial.html#Adding-DataFrame-accessors) 我想我会以这种形式为您提供解决方案:

import vaex
import numpy as np

@vaex.register_dataframe_accessor('mytool', override=True)
class mytool:
    def __init__(self, df):
        self.df = df

    def shift(self, column, n, inplace=False):
        # make a copy without column
        df = self.df.copy().drop(column)
        # make a copy with just the colum
        df_column = self.df[[column]]
        # slice off the head and tail
        df_head = df_column[-n:]
        df_tail = df_column[:-n]
        # stitch them together
        df_shifted = df_head.concat(df_tail)
        # and join (based on row number)
        return df.join(df_shifted, inplace=inplace)

x = np.arange(10)
y = x**2
df = vaex.from_arrays(x=x, y=y)
df['shifted_y'] = df.y
df2 = df.mytool.shift('shifted_y', 2)
df2

它生成一个单列数据报,将其切片、连接并连接回去。全部没有一个内存副本。

我在这里假设一个循环 shift/rotate。

该函数需要稍微修改才能在最新版本 (vaex 4.0.0ax) 中运行,请参阅 this thread

Maarten 的代码应更新如下:

import vaex
import numpy as np

@vaex.register_dataframe_accessor('mytool', override=True)
class mytool:
    def __init__(self, df):
        self.df = df

    # mytool.shift is the analog of pandas.shift() but add the shifted column with specified name to the end of initial df

    def shift(self, column, new_column, n, cyclic=True):
        df = self.df.copy().drop(column)
        df_column = self.df[[column]]
        if cyclic:
            df_head = df_column[-n:]
        else:
            df_head = vaex.from_dict({column: np.ma.filled(np.ma.masked_all(n, dtype=float), 0)})
        df_tail = df_column[:-n]

        df_shifted = df_head.concat(df_tail)
        df_shifted.rename(column, new_column)

        return df_shifted

x = np.arange(10)
y = x**2
df = vaex.from_arrays(x=x, y=y)
df2 = df.join(df.mytool.shift('y', 'shifted_y', 2))
df2