从一个热编码列创建差异列
Create difference columns from one hot encoded columns
我正在尝试在数据集上创建一些额外的特征。我想从我已经热编码的特征中获取空间上下文。例如,我有这个:
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
我希望有一种简单的方法可以做到这一点,计算从列的最后一个值开始的变化并将其输出到相应的列。感谢任何帮助,谢谢。
你可以这样做:
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
,并对每一行执行此操作。
我正在尝试在数据集上创建一些额外的特征。我想从我已经热编码的特征中获取空间上下文。例如,我有这个:
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
我希望有一种简单的方法可以做到这一点,计算从列的最后一个值开始的变化并将其输出到相应的列。感谢任何帮助,谢谢。
你可以这样做:
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
,并对每一行执行此操作。