【问题标题】:Shuffling numpy arrays keeping the respective values改组 numpy 数组,保持各自的值
【发布时间】:2021-05-18 02:25:03
【问题描述】:

我有两个 numpy 数组,都有 100 万个空格,第一个数组中的所有值都与第二个数组中的值对应。我想在保持各自值的同时对它们进行洗牌。我该怎么做?

【问题讨论】:

    标签: python arrays numpy shuffle


    【解决方案1】:

    由于两个数组大小相同,您可以使用Numpy Array Indexing

    def unison_shuffled_copies(a, b):
        assert len(a) == len(b)                  # don't need if we know array a and b is same length
        p = numpy.random.permutation(len(a))     # generate the shuffled indices
        return a[p], b[p]                        # make the shuffled copies using same arrangement according to p
    

    这是引用this answer,有一些变化。

    【讨论】:

      【解决方案2】:

      您可以使用get_state() 跟踪numpy.random.state,并使用set_state() 在随机播放之间重置它。这将使随机播放在两个数组上的行为相同。

      import numpy as np
      
      arr1 = np.arange(9).reshape((3, 3))
      arr2 = np.arange(10,19).reshape((3, 3))
      
      arr1, arr2
      
      # array([[0, 1, 2],
      #        [3, 4, 5],
      #        [6, 7, 8]]),
      # array([[10, 11, 12],
      #        [13, 14, 15],
      #        [16, 17, 18]])
      
      # get state
      state = np.random.get_state()
      np.random.shuffle(arr1)
      arr1
      
      # array([[6, 7, 8],
      #        [3, 4, 5],
      #        [0, 1, 2]])
      
      # reset state and shuffle other array
      np.random.set_state(state)
      np.random.shuffle(arr2)
      arr2
      
      #array([[16, 17, 18],
      #       [13, 14, 15],
      #       [10, 11, 12]])
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2019-07-21
        • 2017-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多