[英]How to pad a one hot array of length n with a 1 on either side of the 1
For example I have the following array: [0, 0, 0, 1, 0, 0, 0]
what I want is [0, 0, 1, 1, 1, 0, 0]
例如我有以下数组:
[0, 0, 0, 1, 0, 0, 0]
我想要的是[0, 0, 1, 1, 1, 0, 0]
If the 1 is at the at the end, for example [1, 0, 0, 0]
it should add only on one side [1, 1, 0, 0]
如果 1 在末尾,例如
[1, 0, 0, 0]
它应该只在一侧添加[1, 1, 0, 0]
How do I add a 1 on either side while keeping the array the same length?如何在保持数组长度相同的同时在任一侧添加 1? I have looked at the numpy pad function, but that didn't seem like the right approach.
我看过 numpy 焊盘 function,但这似乎不是正确的方法。
You can usenp.pad
to create two shifted copies of the array: one shifted 1 time toward the left (eg 0 1 0
-> 1 0 0
) and one shifted 1 time toward the right (eg 0 1 0
-> 0 0 1
).您可以使用
np.pad
创建数组的两个移位副本:一个向左移动 1 次(例如0 1 0
-> 1 0 0
),一个向右移动 1 次(例如0 1 0
-> 0 0 1
)。
Then you can add all three arrays together:然后您可以将所有三个 arrays 加在一起:
0 1 0
1 0 0
+ 0 0 1
-------
1 1 1
Code:代码:
output = a + np.pad(a, (1,0))[:-1] + np.pad(a, (0,1))[1:]
# (1, 0) says to pad 1 time at the start of the array and 0 times at the end
# (0, 1) says to pad 0 times at the start of the array and 1 time at the end
Output: Output:
# Original array
>>> a = np.array([1, 0, 0, 0, 1, 0, 0, 0])
>>> a
array([1, 0, 0, 0, 1, 0, 0, 0])
# New array
>>> output = a + np.pad(a, (1,0))[:-1] + np.pad(a, (0,1))[1:]
>>> output
array([1, 1, 0, 1, 1, 1, 0, 0])
One way using numpy.convolve
with mode == "same"
:使用
numpy.convolve
with mode == "same"
的一种方法:
np.convolve([0, 0, 0, 1, 0, 0, 0], [1,1,1], "same")
Output: Output:
array([0, 0, 1, 1, 1, 0, 0])
With other examples:与其他示例:
np.convolve([1,0,0,0], [1,1,1], "same")
# array([1, 1, 0, 0])
np.convolve([0,0,0,1], [1,1,1], "same")
# array([0, 0, 1, 1])
np.convolve([1,0,0,0,1,0,0,0], [1,1,1], "same")
# array([1, 1, 0, 1, 1, 1, 0, 0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.