在Python中输入数组中特定位置的值

ztigrdn8  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(177)

我有一个列表T2和一个包含不同形状numpy数组的数组X。我想根据T2重新排列这些数组中的值。例如,对于X[0],元素应该根据T2[0]占据位置,而0.应该放置在未提及的位置。类似地,对于X[1],元素应该按照T2[1]占据位置。我给出了预期的输出。

import numpy as np

T2 = [[0, 3, 4, 5], [1, 2, 3, 4]]

X=np.array([np.array([4.23056174e+02, 3.39165087e+02, 3.98049092e+02, 3.68757486e+02]),
       np.array([4.23056174e+02, 3.48895801e+02, 3.48895801e+02, 3.92892424e+02])])

预期输出为

X=array([array([4.23056174e+02, 0, 0, 3.39165087e+02, 3.98049092e+02, 3.68757486e+02]),
      array([0, 4.23056174e+02, 3.48895801e+02, 3.48895801e+02, 3.92892424e+02])])
cvxl0en2

cvxl0en21#

import numpy as np

T2 = ...
X = ...

out = []

for t, x in zip(T2, X):
    temp = np.zeros(max(t) + 1)
    temp[t] = x
    out.append(temp)

out = np.array(out, dtype=object)

输出:

array([array([423.056174,   0.      ,   0.      , 339.165087, 398.049092,
              368.757486])                                               ,
       array([  0.      , 423.056174, 348.895801, 348.895801, 392.892424])],
      dtype=object)

相关问题