numpy 在Python中在数组的多个位置插入零

aij0ehis  于 2023-01-02  发布在  Python
关注(0)|答案(2)|浏览(153)

我有一个列表T2和一个数组X,我想根据T2X的特定位置插入零,例如对于X[0],除了T2[0]X[1]指定的位置外,其他位置都要插入零。除了T2[1]中指定的位置外,必须在所有位置插入零。我给出了当前输出和预期输出。

import numpy as np

T2=[[0, 3, 5, 8, 9, 10, 11],[0, 2, 3, 5, 6, 8, 9, 10, 11]]

X=np.array([np.array([4.17551036e+02, 3.53856161e+02, 2.82754301e+02, 1.34119055e+02,
              6.34573886e+01, 2.08344718e+02, 1.00000000e-24])               ,
       np.array([4.17551036e+02, 3.32821605e+02, 2.94983702e+02, 2.78809292e+02,
              1.26991664e+02, 1.36026510e+02, 8.31512525e+01, 2.07329562e+02,
              1.00000000e-24])                                               ],
      dtype=object)

C1=0.0

index=0

for m in range(0,len(X)):
    for j in range(T2[m][-1]):
        if(j!=T2[m][index]):
            X[m] = np.insert(X[m], j, C1, axis=None)  
        else:
            index+=1

print([X])

当前输出为

[array([array([4.17551036e+02, 0.00000000e+00, 0.00000000e+00, 3.53856161e+02,
              0.00000000e+00, 2.82754301e+02, 0.00000000e+00, 0.00000000e+00,
              1.34119055e+02, 6.34573886e+01, 2.08344718e+02, 1.00000000e-24]),
       array([0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
              0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
              0.00000000e+00, 4.17551036e+02, 3.32821605e+02, 2.94983702e+02,
              2.78809292e+02, 1.26991664e+02, 1.36026510e+02, 8.31512525e+01,
              2.07329562e+02, 1.00000000e-24])                               ],
      dtype=object)]

预期的输出为

[array([array([4.17551036e+02, 0.00000000e+00, 0.00000000e+00, 3.53856161e+02,
              0.00000000e+00, 2.82754301e+02, 0.00000000e+00, 0.00000000e+00,
              1.34119055e+02, 6.34573886e+01, 2.08344718e+02, 1.00000000e-24]),
       array([4.17551036e+02, 0.00000000e+00, 3.32821605e+02, 2.94983702e+02,
              0.00000000e+00, 2.78809292e+02, 1.26991664e+02, 0.00000000e+00,
              1.36026510e+02, 8.31512525e+01, 2.07329562e+02, 1.00000000e-24]) ],
      dtype=object)]
ni65a41a

ni65a41a1#

你把事情弄得太复杂了,你可以把你的问题重新表述为:创建一个数组,其中除了T2中的索引外,所有位置都为零。

def make_array(indices, values):
    rtrn = np.zeros(np.max(indices) + 1, dtype=values.dtype)
    rtrn[indices] = values
    return rtrn

X = np.array([make_array(Ti, Xi) for Ti, Xi in zip(T2, X)], dtype=object)
sg3maiej

sg3maiej2#

您有两个不同的任务,复合数据结构使问题复杂化,如果您将数据拆分为:
T1 = [0、3、5、8、9、10、11]
T2 = [0、2、3、5、6、8、9、10、11]

X1 = np.array([4.17551036e+02, 3.53856161e+02, 2.82754301e+02, 1.34119055e+02,
              6.34573886e+01, 2.08344718e+02, 1.00000000e-24])

X2 = np.array([4.17551036e+02, 3.32821605e+02, 2.94983702e+02, 2.78809292e+02,
              1.26991664e+02, 1.36026510e+02, 8.31512525e+01, 2.07329562e+02,
              1.00000000e-24])

您的两个不同问题可以通过以下方式解决:

Y1 = np.zeros((12))
for i, value in zip(T1,X1):
    Y1[i] = value

Y2 = np.zeros((12))
for i1, i2 in enumerate(T2):
    Y2[i2] = X2[i1]

相关问题