我有一个形状:(15,2)
的数组。我还有另一个数组值:[0, 3, 5]
.
我想在第一个数组中创建另一个列,其值来自第二个数组,其中前5行值为0,第6-10行值为3,最后5行值为5。
一样:
[0,
0,
0,
0,
0,
3,
3,
3,
3,
3,
5,
5,
5,
5,
5]
是否有任何numpy方法可以做到这一点?
谢谢!
您可以使用numpy的内置repeat
和stack
:
a = np.zeros((15,2))
b = np.array([0,3,5])
np.hstack((a, np.repeat(b,5)[:,None]))
输出:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 3.]
[0. 0. 3.]
[0. 0. 3.]
[0. 0. 3.]
[0. 0. 3.]
[0. 0. 5.]
[0. 0. 5.]
[0. 0. 5.]
[0. 0. 5.]
[0. 0. 5.]]
rand = np.random.random((15,2)) # shape is (15,2)
vals = np.array([0,3,5]) # shape is (3,)
res = np.concatenate(([np.full((rand.shape[0]//vals.shape[0],), val) for val in vals]), axis=0)
res
输出:
array([0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5])
最后,
final = np.hstack((rand, res.reshape(15,1)))
final
输出:
array([[0.29759807, 0.60548479, 0. ],
[0.61242249, 0.46456274, 0. ],
[0.86172011, 0.2963868 , 0. ],
[0.91728575, 0.36366023, 0. ],
[0.56488556, 0.82130321, 0. ],
[0.59482141, 0.46148353, 3. ],
[0.7762271 , 0.25415058, 3. ],
[0.09176551, 0.9687253 , 3. ],
[0.06473259, 0.34686598, 3. ],
[0.69542414, 0.15540001, 3. ],
[0.02880707, 0.23169327, 5. ],
[0.90004256, 0.22145591, 5. ],
[0.61596969, 0.46807342, 5. ],
[0.02263769, 0.68522023, 5. ],
[0.81777274, 0.58145853, 5. ]])
使用np.concatenate
.
- 将第二个数组转换为2d"矢量";数组,每行有1列
a = [0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5] # your list of [0, 3, 5]
a = np.array([a]).T # [ [0], [0], [0], ..., [5] ] the "vector" array
那么简单
b = np.array([[i, i +1] for i in range(15)]) # some example 15x2 array
print(np.concatenate((b, a), axis=1))
输出为
array([[ 0, 1, 0],
[ 1, 2, 0],
[ 2, 3, 0],
[ 3, 4, 0],
[ 4, 5, 0],
[ 5, 6, 3],
[ 6, 7, 3],
[ 7, 8, 3],
[ 8, 9, 3],
[ 9, 10, 3],
[10, 11, 5],
[11, 12, 5],
[12, 13, 5],
[13, 14, 5],
[14, 15, 5]])