NumPy: sorting 3D array but keeping 2nd dimension assigned to first

后端 未结 2 519
说谎
说谎 2021-01-15 15:03

I have an array that represents poker cards held by players. Each player holds 6 cards and the cards have a value of 1-12 and have a corresponding suit of 1-4.

The f

2条回答
  •  别那么骄傲
    2021-01-15 15:55

    First you need a single value which you can use to sort your cards. An easy one would be value*4 + suit:

    sortval = deck[:,:,0]*4+deck[:,:,1]
    sortval *= -1 # if you want largest first
    

    Then you use np.argsort to find out which index belongs where and use it to sort your decks. It sorts along the last axis on default, which is what we want.

    sortedIdx = np.argsort(sortval)
    

    Now you can use it to sort your deck like this:

    deck = deck[np.arange(len(deck))[:,np.newaxis],sortedIdx]
    

    The np.arange... part makes sure that every second dimension index array from sortedIdx is paired with the right first dimension index.

    The whole thing:

    import numpy as np
    
    deck = np.array([[[  6.,   2.],
                      [ 10.,   1.],
                      [  5.,   1.],
                      [  9.,   2.],
                      [  4.,   1.],
                      [  3.,   2.],
                      [ 11.,   2.]],
    
                     [[  6.,   2.],
                      [  2.,   2.],
                      [  2.,   3.],
                      [ 11.,   1.],
                      [ 11.,   3.],
                      [  5.,   3.],
                      [  4.,   4.]]])
    
    sortval = deck[:,:,0]*4+deck[:,:,1]
    sortval *= -1 # if you want largest first
    sortedIdx = np.argsort(sortval)
    deck = deck[np.arange(len(deck))[:,np.newaxis],sortedIdx]
    print(deck)
    

    Will print:

    [[[ 11.   2.]
      [ 10.   1.]
      [  9.   2.]
      [  6.   2.]
      [  5.   1.]
      [  4.   1.]
      [  3.   2.]]
    
     [[ 11.   3.]
      [ 11.   1.]
      [  6.   2.]
      [  5.   3.]
      [  4.   4.]
      [  2.   3.]
      [  2.   2.]]]
    

提交回复
热议问题