【问题标题】:Shift masked values of to the end of a 2D python array?将掩码值移到 2D python 数组的末尾?
【发布时间】:2018-08-08 23:16:50
【问题描述】:

假设我们有一个 2D numpy 数组,我们使用 np.ma.masked_where 来屏蔽一些元素。在每一行中,我们希望将所有被屏蔽的元素移动到末尾,同时保留其余元素的顺序。有没有一种简单的无循环方式来做到这一点?

例如,假设我们有以下蒙面的二维矩阵:

a = [1, --, 2
     4, 3, --
     --, --,5]

我们想返回:

a = [1, 2, --
     4, 3, --
     5,--, --]

【问题讨论】:

    标签: python arrays sorting bit-shift masked-array


    【解决方案1】:

    我没有发现任何ma函数可以实现这一点,但我认为你可以先对掩码数组进行排序

    a = np.arange(9).reshape(3, 3)
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])
    
    np.ma.masked_where(a % 2 == 0, a)
    masked_array(data =
     [[-- 1 --]
     [3 -- 5]
     [-- 7 --]],
                 mask =
     [[ True False  True]
     [False  True False]
     [ True False  True]],
           fill_value = 999999)
    
    
    a = a[np.arange(a.shape[0]).reshape(-1, 1), np.argsort(a % 2 == 0, axis=1, kind='mergesort')]
    array([[1, 0, 2],
           [3, 5, 4],
           [7, 6, 8]])
    
    np.ma.masked_where(a %2 == 0, a)
    masked_array(data =
     [[1 -- --]
     [3 5 --]
     [7 -- --]],
                 mask =
     [[False  True  True]
     [False False  True]
     [False  True  True]],
           fill_value = 999999)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-22
      • 2017-07-17
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2021-09-09
      相关资源
      最近更新 更多