英文:
Vectorized merged python arrays
问题
你可以使用以下的numpy操作来合并xarr和yarr以获得所需的结果数组,而不使用循环或numpy.diag或numpy.eye等函数:
result = (xarr.T @ yarr.T).T
这将产生所需的结果数组,而不需要使用循环或特定的numpy函数。
英文:
Say you have an array x that is 3x3 as follows:
>>> xarr
array([[0., 0., 0.],
[0., 0., 0.],
[1., 1., 1.]])
Similarly a y array as follows:
>>> yarr
array([[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]])
Question is: Is there a way to merge (or use in any vectorized way) xarr and yarr in order to get a result array that looks like this:
>>> result
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
The idea is to get the result array without using loops and of course without the numpy.diag or numpy.eye etc..
答案1
得分: 1
这是一种方法。
import numpy as np
x = np.array([[0, 0, 0],
[0., 0., 0.],
[1., 1., 1.]])
y = np.array([[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]])
c = np.zeros_like(x)
x = x.nonzero()[1]
y = y.nonzero()[0]
c[x, y] = 1
print(c)
英文:
This is one way.
import numpy as np
x =np.array([[0, 0, 0],
[0., 0., 0.],
[1., 1., 1.]])
y = np.array([[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]])
c = np.zeros_like(x)
x = x.nonzero()[1]
y = y.nonzero()[0]
c[x,y] = 1
print(c)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论