仅对列表中的正数进行排名,在 Pandas 中负数应替换为 -1
python 414
原文标题 :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]
回复
我来回复-
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.sort
或sorted
对结果列表进行排序。最终代码:
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年前 -
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年前