矢量化合并的Python数组

huangapple go评论58阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月16日 02:26:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定