【问题标题】:Wrapping a numpy array element to integer将 numpy 数组元素包装为整数
【发布时间】:2015-06-26 21:17:16
【问题描述】:

我有一个尝试在循环中访问的子图列表:

 index=[5,3,4,1,1,3,4,2,3,4,2,2,3,3,2,4]
 subgraph=[[subgraph1],[subgraph2],[subgraph3],[subgraph4],[subgraph5]]
 for i in range(len(index)):
      for j in range(i+1,len(index)):
          if index[j]==index[i]
              continue
          testgraphi=copy.copy(subgraph[index[i]])
          testgraphj=copy.copy(subgraph[index[j]])

所以在第一个循环中,testgraphi 将被分配subgraph5testgraphj 将被分配subgraph3。但是,当我尝试这种方法时,我返回了一个错误list indices must be integers, not numpy.float64。这是合乎逻辑的,因为index 在我的程序的整个范围内实际上被初始化为一个 numpy 数组(并且它必须保持这种方式)。所以我的问题是,我怎样才能转换这个值,以便它可以用作我的子图列表的索引?这样testgraph在初始化的时候,会获取循环所在的index的值,并以此来定义返回哪个list index?

【问题讨论】:

    标签: python arrays numpy indexing casting


    【解决方案1】:

    您可以通过以下操作将numpy.float64 转换为浮动:var.item()。然后将其转换为整数,以便您可以将其用作索引:int(var.item())

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      new_index = np.asarray(index, dtype=np.int32)
      

      这应该将索引中的所有值转换为整数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-13
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 2022-01-02
        • 1970-01-01
        • 2011-05-12
        • 1970-01-01
        相关资源
        最近更新 更多