簡體   English   中英

將索引附加到numpy數組

[英]appending indices to numpy array

我通過遍歷行和列並關聯值來制作變量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_matrix 我可以打印值,但無法弄清楚如何將它們存儲在變量中,以便以后可以使用它們為索引編制索引。

我想要:

  1. 創建一個變量ind_matrix ,該變量是上述語句為true的索引。

  2. 我想使用ind_matrix在我的相關矩陣內ind_matrix索引。 我希望能夠索引整行以及上述語句為true的確切值( enc_dict[enc_row] == ret_dict[ret_col]

我嘗試了ind_matrix = np.append(ind_matrix, [[enc_row, ret_col]]) ,它為我提供了正確的值,但是由於某種原因,它在#之前有很多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]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM