如何根据另一个数组的行分配 np 数组的行?

How to assign rows of np array according to rows of another array?

我想构建一个点数组,其中每一行都取决于时间步长数组的相应行,如:

steps = 5
output = np.empty((steps, 3))
timesteps = np.linspace(0, 1, steps)

for i, step in enumerate(timesteps):
    output[i] = [sin(step), cos(step), 0]

预期输出:

[[0.         1.         0.        ]
 [0.24740396 0.96891242 0.        ]
 [0.47942554 0.87758256 0.        ]
 [0.68163876 0.73168887 0.        ]
 [0.84147098 0.54030231 0.        ]]

如何矢量化此操作?


我可以像这样独立分配每一列:

out[:, 0] = np.sin(timesteps)
out[:, 1] = np.cos(timesteps)
out[:, 2] = 0

但如果可能的话,我想保持基于行的方法以提高可读性。

我在想

output[:] = [np.sin(timesteps[:]), np.cos(timestep[:]), 0]

但显然这不起作用,因为设置了带有序列的数组元素。

您可以通过以下方式创建一个 numpy 数组:
np.array([np.sin(timesteps), np.cos(timesteps), [0]*len(timesteps)])

然而,这会将正弦设置为第一行,将余弦设置为第二行,依此类推。要将它们从行更改为列,您可以使用 transpose() 方法,也可以通过 .T 属性访问。最后你会得到:

output = np.array([np.sin(timesteps), 
                   np.cos(timesteps), 
                   [0]*len(timesteps)]).transpose()

要么
output = np.array([np.sin(timesteps), np.cos(timesteps), [0]*len(timesteps)]).T

我发现这与您尝试的非常接近,并且我猜这对“可读性”问题没有影响。要检查这确实是您想要的:

import numpy as np

steps = 5
output = np.empty((steps, 3))
timesteps = np.linspace(0, 1, steps)

for i, step in enumerate(timesteps):
    output[i] = [np.sin(step), np.cos(step), 0]

output -= np.array([np.sin(timesteps), np.cos(timesteps), [0]*len(timesteps)]).transpose()

print(output)

> [[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]

注意:[0]*len(timesteps) 创建一个大小为 len(timesteps) 的列表,仅填充零

我有这样的东西,你能试试吗?

output[:] = [np.sin(timesteps[:]), np.cos(timestep[:]), 0]

这是我的解决方案:

import numpy as np
steps = 5
timesteps = np.linspace(0, 1, steps)

out=np.concatenate(([np.sin(timesteps)],[np.cos(timesteps)],[np.zeros(steps)]))

out=out.transpose()

out
array([[0.        , 1.        , 0.        ],
       [0.24740396, 0.96891242, 0.        ],
       [0.47942554, 0.87758256, 0.        ],
       [0.68163876, 0.73168887, 0.        ],
       [0.84147098, 0.54030231, 0.        ]])

我认为这会有所帮助,如果问题仍然存在,请告诉我。