【问题标题】:Specific column for each row in numpy [duplicate]numpy中每一行的特定列[重复]
【发布时间】:2017-09-25 18:58:07
【问题描述】:

我想为每一行指定特定的列号,如下所示。 d 是类似 (embedding_id x n_vocab) 的数据,t 是正确 embedding_id 的列表。

然后,我可以创建result,如下所示。数据很好,但我认为这并不聪明。如何以其他智能方式创建result

 t = np.random.randint(10, size=(32,))                                          
 d = np.random.randn(30, 32)                                                    

 result = []                                                                    
 for a,b in zip(d.transpose(), t):                                              
     print(a[b])                                                                
     result.append(a[b]) # I don't think this is good way                                                  
 result = np.array(result).astype(float)                                        
 print(result)                                                                  
 print(result.shape) # (32,). 

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    你可以index这样;使用numpy.arrange 创建列索引并将其与t 一起使用(这称为高级索引):

    d[t, np.arange(len(t))]
    

    (d[t, np.arange(len(t))] == result).all()
    # True
    

    【讨论】:

    • 太好了。可以肯定的是,第一个元素t 是特定的列号,第二个元素是特定的行。所以我想做的是在每一行的特定列中提取值。我会接受你的回答。谢谢!
    • 你的理解是正确的。除了我会说t 是行索引,而按照惯例,第二个列索引。
    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多