从一个热编码列创建差异列

问题描述 投票:0回答:1

我正在尝试在数据集上创建一些额外的功能。我想从我已经有一个热编码的功能中获取空间上下文。例如,我有这个:

    F1    F2    F3    F4
1   0     1     1     0
2   1     0     1     1
3   1     0     0     0
4   0     0     0     1

我想在这里针对值创建一些新列:

    F1    F2    F3    F4    S1    S2    S3    S4
1   0     1     1     0     0     2     1     0
2   1     0     0     1     1     0     0     3
3   1     0     0     0     1     0     0     0
4   0     0     0     1     0     0     0     4

我希望有一种简单的方法可以做到这一点,从列的最后一个值计算更改并将其输出到相应的列。任何帮助表示赞赏,谢谢。

python pandas feature-extraction
1个回答
1
投票

你可以这样做:

def func(x):
    # create result array
    result = np.zeros(x.shape, dtype=np.int)

    # get indices of array distinct of zero
    w = np.argwhere(x).ravel()

    # compute the difference between consecutive indices and add the first index + 1
    array = np.hstack(([w[0] + 1], np.ediff1d(w)))

    # set the values on result
    np.put(result, w, array)

    return result


columns = ['S{}'.format(i) for i in range(1, 5)]
s = pd.DataFrame(df.ne(0).apply(func, axis=1).values.tolist(),
                 columns=columns)

result = pd.concat([df, s], axis=1)
print(result)

产量

   F1  F2  F3  F4  S1  S2  S3  S4
0   0   1   1   0   0   2   1   0
1   1   0   0   1   1   0   0   3
2   1   0   0   0   1   0   0   0
3   0   0   0   1   0   0   0   4

请注意,您需要导入numpy(import numpy as np)才能使func正常工作。我们的想法是找到零差异的指数计算连续值之间的差异,将第一个值设置为index + 1,并为每一行执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.