Python间接索引

时间:2016-04-13 03:44:09

标签: python matrix-indexing

如果您知道如何操作,这可能是一个非常简单的问题,但我无法弄清楚语法:

我有一个5x10零的数组:KCSUser.loginWithUsername( "kinvey", password: "12345", withCompletionBlock: { (user: KCSUser!, errorOrNil: NSError!, result: KCSUserActionResult) -> Void in if errorOrNil == nil { //the log-in was successful and the user is now the active user and credentials saved // Put your code to save the object here } else { //there was an error with the update save } } ) 和索引的数组5x1:y1 = np.zeros((5,10))。对于index=np.array([2,3,2,5,6])的每一行,我想在索引给出的列处设置1。结果看起来像

y1

任何人都可以帮忙:-)?

2 个答案:

答案 0 :(得分:0)

只需使用枚举()

即可
import numpy as np

y1 = np.zeros((5,10))
index=np.array([2,3,2,5,6])


for i,item in enumerate(y1):
    item[index[i]] = 1

print(y1)
# [[ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
 # [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
 # [ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
 # [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
 # [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]]

这样做你想要的吗?

答案 1 :(得分:0)

您可以使用array[index_1, index_2]进行多维数组索引。对于你的问题:

y1[range(y1.shape[0]), index] = 1

range(y1.shape [0])生成数组[0,1,...,n-1],其中n是y1中的行数。此数组是您的行索引,index是您的列索引。