【问题标题】:convert np.where array to list将 np.where 数组转换为列表
【发布时间】:2018-04-17 15:27:18
【问题描述】:

我尝试使用np.where 获取数组的索引,并希望以这样的方式连接列表,从而为我提供一维列表。是否可以?

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
y= np.where(l==10)
p=np.where(l==5)

如果我打印 y 和 p,它们会给我

(array([ 0,  3,  6, 10, 14]),)

(array([ 5, 11, 13]),)

添加后会生成一个元组列表。但是我想要的输出是这样的:

[0,3,6,10,14,5,11,13]

【问题讨论】:

  • where 生成一个数组元组,每个维度一个。

标签: python arrays list numpy


【解决方案1】:

既然有很多其他的解决方案,我会告诉你另一种方式。

您可以使用np.isin 来测试数组中的正确值:

goovalues = {5, 10}
np.where(np.isin(l, goodvalues))[0].tolist() #  [0, 3, 6, 10, 14, 5, 11, 13]

【讨论】:

    【解决方案2】:

    您可以concatinate 两个数组,然后将结果转换为列表:

    result = np.concatenate((y[0], p[0])).tolist()
    

    【讨论】:

    • 它将值转换为浮点数。我如何让它们保持完整?
    • @SunAns 你为什么这么认为?试试type(np.concatenate((y[0], p[0])).tolist()[0]),你会发现它是int
    【解决方案3】:

    您可以使用y[0]p[0] 访问列表,然后附加结果。只需添加以下行:

    r = np.append(y[0], p[0])
    

    r 将是一个 np.array ,其中包含您要求的值。如果您希望将其作为列表,请使用 list(r)

    【讨论】:

      【解决方案4】:

      使用concatenate 的方法:

      import numpy as np
      
      l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
      y = np.where(l==10)[0]
      p = np.where(l==5)[0]
      k = np.concatenate((y, p))
      
      print(k) # [ 0  3  6 10 14  5 11 13]
      

      【讨论】:

        【解决方案5】:

        在一行中现有的另一个补充。

        l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
        
        y = np.where((l == 10) | (l == 5))[0]
        

        Numpy 可与 &(与)、|(或)和 ~(非)等运算符一起使用。 where 函数返回一个元组,以防你传递一个布尔数组并因此传递索引 0。

        希望这会有所帮助。

        【讨论】:

          【解决方案6】:

          试试这个

          y = [items for items in y[0]]
          p = [items for items in p[0]]
          

          然后

          new_list = y + p
          

          【讨论】:

            猜你喜欢
            • 2019-06-24
            • 2011-11-26
            • 1970-01-01
            • 2018-01-06
            • 2019-01-23
            相关资源
            最近更新 更多