Python 向numpy数组追加索引

Python 向numpy数组追加索引,python,arrays,numpy,Python,Arrays,Numpy,我通过对行和列进行迭代并关联值来生成一个变量corr_matrix import numpy as np import random enc_dict = {k: int(random.uniform(1,24)) for k in range(24)} ret_dict = {k: int(random.uniform(1,24)) for k in range(24)} corr_matrix=np.zeros((24,24)) ind_matrix = np.zeros((24,24)

我通过对行和列进行迭代并关联值来生成一个变量
corr_matrix

import numpy as np
import random

enc_dict = {k: int(random.uniform(1,24)) for k in range(24)}
ret_dict = {k: int(random.uniform(1,24)) for k in range(24)}

corr_matrix=np.zeros((24,24))
ind_matrix = np.zeros((24,24))

data = np.random.rand(24,24)
for enc_row in range(0,24):
            for ret_col in range(0,24):
                corr_matrix[enc_row, ret_col] = np.corrcoef(data[enc_row,:], data[ret_col,:])[0,1]
                if enc_dict[enc_row] == ret_dict[ret_col]:
                    ind_matrix = np.append(ind_matrix, [[enc_row, ret_col]])
我想将索引存储在矩阵中,其中
enc_dict[enc_row]==ret_dict[ret_col]
作为用于索引
corr_矩阵的变量。我可以打印这些值,但我不知道如何将它们存储在变量中,以便以后使用它们进行索引

我想:

  • 制作一个变量,
    ind_matrix
    ,它是上述语句为真的索引

  • 我想使用
    ind_matrix
    在我的相关矩阵中建立索引。我希望能够索引整行以及上面语句为真的确切值(
    enc_dict[enc_row]==ret_dict[ret_col]


  • 我尝试了
    ind_matrix=np.append(ind_matrix,[[enc_row,ret_col]])
    ,它给出了正确的值,但由于某些原因,它在#s之前有很多0。此外,它不允许我将每对点调用在一起以用于索引。我希望能够执行类似于
    corr_matrix[ind_matrix[1]]

    的操作。以下是您代码的修改版本,其中包含一些建议和注释:

    import numpy as np
    
    # when indices are 0, 1, 2, ... don't use dictionary
    # also for integer values use randint
    enc_ = np.random.randint(1, 24, (24,))
    ret_ = np.random.randint(1, 24, (24,))
    
    data = np.random.rand(24,24)
    # np.corrcoef is vectorized, no need to loop:
    corr_matrix = np.corrcoef(data)
    # the following is the clearest, but maybe not the fastest way of generating
    # your index array:
    ind_matrix = np.argwhere(np.equal.outer(enc_, ret_))
    
    # this can't be used for indexing directly, you'll have to choose
    # one of the following idioms
    
    # EITHER spread to two index arrays
    I, J = ind_matrix.T
    # or directly I, J = np.where(np.equal.outer(enc_, ret_))
    # single index
    print(corr_matrix[I[1], J[1]])
    # multiple indices
    print(corr_matrix[I[[1,2,0]], J[[1,2,0]]])
    # whole row
    print(corr_matrix[I[1]])
    
    # OR use tuple conversion
    ind_matrix = np.array(ind_matrix)
    # single index
    print(corr_matrix[(*ind_matrix[1],)])
    # multiple indices
    print(corr_matrix[(*zip(*ind_matrix[[1,2,0]],),)])
    # whole row
    print(corr_matrix[ind_matrix[1, 0]])
    
    # OR if you do not plan to use multiple indices
    as_tuple = list(map(tuple, ind_matrix))
    # single index
    print(corr_matrix[as_tuple[1]])
    # whole row
    print(corr_matrix[as_tuple[1][0]])
    

    在你的问题中打a,不要使用np.append。它很慢,很难正确使用。我应该用什么来代替呢?@Maria,我发现仅仅创建一个简单的旧python列表,然后用
    vstack
    hstack
    array
    将其转换为一个数组,在可读性和性能方面效果最好。