Python : 如何对列表中的元素进行排名?
Python : how to rank an element among a list?
假设我有一个未排序的数据框:
df = pandas.DataFrame({'A': [6, 2, 3, 5]})
我有一个输入:
input = 3
我想查找我的输入在列表中的排名。这里:
expected_rank_in_df(input) = 2
# Because 2 < 3 < 5 < 6
Assumption : The input is always included in the dataframe. So for example, I will not find the position of "4" in this df.
第一个想法是像这里这样使用::
df.rank()
但这对我来说似乎太过分了,因为我不需要对整个专栏进行排名。也许不是?
您可以通过 numpy.where
和第一个 True
:
的布尔掩码来获取匹配值的第一个位置
a = 3
print (np.where(np.sort(df['A']) == a)[0][0] + 1)
2
如果默认RangeIndex:
a = 3
print (df['A'].sort_values().eq(3).idxmax())
2
另一个想法是通过 sum
:
计算 True
个值
print (df['A'].gt(3).sum())
2
如果您确定输入在列中,则排名将等于
df[df > input].count()
这有意义吗?如果您打算多次调用它,那么只对列进行排序可能是值得的。但如果您只关心几个输入,这可能会更快。
假设我有一个未排序的数据框:
df = pandas.DataFrame({'A': [6, 2, 3, 5]})
我有一个输入:
input = 3
我想查找我的输入在列表中的排名。这里:
expected_rank_in_df(input) = 2
# Because 2 < 3 < 5 < 6
Assumption : The input is always included in the dataframe. So for example, I will not find the position of "4" in this df.
第一个想法是像这里这样使用:
df.rank()
但这对我来说似乎太过分了,因为我不需要对整个专栏进行排名。也许不是?
您可以通过 numpy.where
和第一个 True
:
a = 3
print (np.where(np.sort(df['A']) == a)[0][0] + 1)
2
如果默认RangeIndex:
a = 3
print (df['A'].sort_values().eq(3).idxmax())
2
另一个想法是通过 sum
:
True
个值
print (df['A'].gt(3).sum())
2
如果您确定输入在列中,则排名将等于
df[df > input].count()
这有意义吗?如果您打算多次调用它,那么只对列进行排序可能是值得的。但如果您只关心几个输入,这可能会更快。