仅对列表中的正数进行排名,在 Pandas 中负数应替换为 -1

原文标题Ranking only positive numbers in a list , and negative number should replace with -1 in Pandas

可重现的代码:

import numpy as np
lst =  [-69,-68,-58,-39,-18,-11,-10,-9,-8,0,2,7,7,21,31,31,34,46,49,89,128]

试过代码:

sorted_list = [sorted(lst).index(x) for x in lst]
sorted_list

预期输出:

[-1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

原文链接:https://stackoverflow.com//questions/71555346/ranking-only-positive-numbers-in-a-list-and-negative-number-should-replace-wit

回复

我来回复
  • Stef的头像
    Stef 评论

    您可以使用map或列表推导式将每个负数替换为 -1。这可以通过条件来完成:

    # list comprehension
    l = [(-1 if x < 0 else x) for x in l]
    
    # map
    l = list(map(lambda x: -1 if x < 0 else 0, l))
    

    或者如果数字是整数,那么-1是可能的“最高”负数,所以你可以使用max

    # list comprehension
    l = [max(-1, x) for x in l]
    
    # map
    l = list(map(lambda x: max(-1, x), l))
    

    然后您可以使用list.sortsorted对结果列表进行排序。

    最终代码:

    def sorted_and_minus1(l):
        return sorted(max(-1, x) for x in l)
    
    lst =  [-69,-68,-58,-39,-18,-11,-10,-9,-8,0,2,7,7,21,31,31,34,46,49,89,128]
    sorted_lst = sorted_and_minus1(lst)
    print(sorted_lst)
    # [-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 7, 7, 21, 31, 31, 34, 46, 49, 89, 128]
    
    2年前 0条评论
  • Sowjanya R Bhat的头像
    Sowjanya R Bhat 评论

    创建一个熊猫系列,然后用 -1 替换负数,然后对它们进行排序:

    import pandas as pd 
    import numpy as np
    lst =  [-69,-68,-58,-39,-18,-11,-10,-9,-8,0,2,7,7,21,31,31,34,46,49,89,128]
    s = pd.Series(lst)
    s[s<0] = -1
    print(s.sort_values())
    
    2年前 0条评论