2

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

vaex我在文档中找不到任何可比的东西。

4

2 回答 2

5

不,我们还不支持 ( https://github.com/vaexio/vaex/issues/660 )。因为 vaex 是可扩展的(请参阅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

它生成一个单列数据报,将其分割、连接并连接回来。所有这些都没有一个内存副本。

我在这里假设一个循环移位/旋转。

于 2020-04-07T07:54:04.427 回答
1

该功能需要稍作修改才能在最新版本(vaex 4.0.0ax)中工作,请参阅此线程

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
于 2020-12-26T19:49:02.617 回答