How to sort a numpy array with key as isnan?

前端 未结 3 1698
遥遥无期
遥遥无期 2020-12-21 16:26

I have a numpy array like

np.array([[1.0, np.nan, 5.0, 1, True, True, np.nan, True],
       [np.nan, 4.0, 7.0, 2, True, np.nan, False, True],
       [2.0, 5         


        
3条回答
  •  再見小時候
    2020-12-21 17:12

    Since you have an object array anyway, do the sorting in Python, then make your array. You can write a key that does something like this:

    from math import isnan
    
    def key(x):
        if isnan(x):
            t = 3
            x = 0
        elif isinstance(x, bool):
            t = 2
        else:
            t = 1
        return t, x
    

    This key returns a two-element tuple, where the first element gives the preliminary ordering by type. It considers all NaNs to be equal and greater than any other type.

    Even if you start with data in a DataFrame, you can do something like:

    values = [list(sorted(row, key=key)) for row in data.values]
    values = np.array(values, dtype=np.object)
    

    You can replace the list comprehension with np.apply_along_axis if that suits your needs better:

    values = np.apply_along_axis(lambda row: np.array(list(sorted(row, key=key))),
                                 axis=1, arr=data.values)
    

提交回复
热议问题