【问题标题】:2 Column Array Rank with tiebreaker and Save Python numpy2 列数组排名与决胜局和保存 Python numpy
【发布时间】:2014-04-04 21:09:14
【问题描述】:

我需要能够基于单个列对数组进行排名,然后再次使用第二列作为基本的决胜局,然后将这两个排名保存到数据库中

数组:

array = np.array(
    [(70,3,100),
     (72,3,101),
     (70,2,102)], dtype=[
                  ('score','int8'),
                  ('tiebreaker','int8'),
                  ('row_id','int8')])
array['score'] = array([70, 72, 70], dtype=int8)

仅使用“分数”列的第一排名将返回

(1,3,1)

然后使用'score'和'tiebreaker'列的第二个Rank排名

(2,3,1)

然后我想将这两个等级保存到数据库中,例如:

result1 = Result.objects.get(id=array[0]['row_id'])
result1.relative_rank = 1
result1.absolute_rank = 2
results.save()

【问题讨论】:

  • array.sort(order=['score', 'tiebreaker'])

标签: python arrays django numpy scipy


【解决方案1】:

你可以使用scipy.stats.rankdata,如下:

In [10]: a
Out[10]: 
array([(70, 3, 100), (72, 3, 101), (70, 2, 102)], 
      dtype=[('score', 'i1'), ('tiebreaker', 'i1'), ('row_id', 'i1')])

In [11]: from scipy.stats import rankdata

一等奖:

In [12]: rankdata(a['score'], method='min').astype(int)
Out[12]: array([1, 3, 1])

二等奖:

In [13]: rankdata(256*a['score'] + a['tiebreaker'], method='min').astype(int)
Out[13]: array([2, 3, 1])

第二个等级 (256*a['score'] + a['tiebreaker']) 中使用的值依赖于类型为 int8 的数据。

检查文档字符串以查看不同的method 是否更适合第二级。如果你知道第二名不会有平局,那么方法就无所谓了。

【讨论】:

  • 如何将排名数组推入该结果数组的另一列? a['rank_1'] = array([1,3,1])
  • 您可以在创建数组时创建 rank_1 字段以及原始字段(填充虚拟值,例如 0)。例如。 a = array([(70, 3, 100, 0), ...], dtype=[('score', 'int8'), ..., ('rank_1', int)]).
猜你喜欢
  • 2019-06-15
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多