【问题标题】:Convert data from numpy where() [duplicate]从 numpy where() 转换数据 [重复]
【发布时间】:2020-06-25 23:01:30
【问题描述】:

我有大量数据,我正在尝试将其转换为特定的形式(这样我就可以重复使用其他人的代码)。这是我正在使用的一个较小集合的示例。

>>> a = np.array([[0, 1, 2], [0, 2, 4],  [0, 3, 6]])
>>> a
array([[0, 1, 2],
       [0, 2, 4],
       [0, 3, 6]])
>>> np.where(a==0)
(array([0, 1, 2]), array([0, 0, 0]))

所以,它返回的是一个元组中的两个数组。
为 0 的地方是 (0,0)、(1,0) 和 (2,0)

我想把这些数据变成这个表格:

[(0,0), (1,0),  (2,0)]

这是一个元组列表。

感谢任何指针。

【问题讨论】:

  • w = np.where(a==0)之后,试试print(list(zip(w[0], w[1])))
  • 或者为了更通用(不一定是二维),使用list(zip(*w))

标签: python arrays list numpy tuples


【解决方案1】:

试试numpy.argwhere

[tuple(x) for x in numpy.argwhere(a==0)]

【讨论】:

    【解决方案2】:
    list(zip(*np.where(a==0)))
    

    这是如何工作的:

    zip 函数将产生一个元组序列,包括:

    • 元组包含每个参数中的元素 0
    • 元组包含每个参数中的元素 1
    • ……等等……

    因此,如果zip 的参数是numpy.where 返回的元组的元素,则此序列的元素将采用所需的形式。使用* 意味着根据需要扩展此元组以分隔位置参数,而不是传入元组本身。然后只需要调用list() 来遍历zip 返回的迭代器并将值转换为列表。

    例子:

    >>> a = np.array([[0, 1, 2], [0, 2, 4], [0, 3, 6]])  # array in the question
    
    >>> list(zip(*np.where(a==0)))
    [(0, 0), (1, 0), (2, 0)]  # list of 2-tuples
    
    >>> a = a.reshape(1,3,3)  # now a 3d-array (adds slowest varying dimension of size 1)
    
    >>> list(zip(*np.where(a==0)))
    [(0, 0, 0), (0, 1, 0), (0, 2, 0)]  # now you get a list of 3-tuples
    

    【讨论】:

      【解决方案3】:

      你需要这个:

      np.argwhere(a==0)
      

      您的示例的输出:

      [[0 0]
       [1 0]
       [2 0]]
      

      如果您需要元组列表:

      list(map(tuple,np.argwhere(a==0)))
      

      输出:

      [(0, 0), (1, 0), (2, 0)]
      

      【讨论】:

        猜你喜欢
        • 2021-03-26
        • 2019-07-25
        • 1970-01-01
        • 2021-11-29
        • 2018-05-03
        • 2021-12-20
        • 2017-05-09
        • 2019-09-10
        • 2016-03-25
        相关资源
        最近更新 更多