我需要将所有元素从第一个列表放置到第二个列表的第k个位置。其中k = 0,1,2...
,n是单个数字。目前,我正在执行此操作(使用numpy)
#create numpy array
positionList = np.array([])
positions = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
epochs = np.array([10, 11, 12])
for pos,epoch in zip(positions,epochs):
position = np.insert(pos,0,epoch)
if len(positionList) > 0:
positionList = np.concatenate((positionList,position))
else:
positionList = position
positionList = np.around(positionList,1).tolist()
#expected output [10, 1, 2, 3, 11, 4, 5, 6, 12, 7, 8, 9]
位置为2D。我正在尝试找到最有效的方法(时间和空间)来用numpy做到这一点。
注意:以上代码确实有效。我只是想使其高效。
只需使用axis
参数np.concatenate()
:
import numpy as np
positions = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
epochs = np.array([10, 11, 12])
print(np.concatenate([epochs[..., None], positions], axis=1).ravel())
# [10 1 2 3 11 4 5 6 12 7 8 9]
编写此代码时不会损害循环。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句