[英]Efficient way to compare the values of 3 lists in Python?
I have 3 lists with similar float values in a1, a2, a3 (whose lengths are equal). 我在a1,a2,a3(长度相等)中有3个具有相似浮点值的列表。
for i in length(a1,a2,a3):
Find the increasing / decreasing order of a1[i], a2[i], a3[i]
Rank the values based on the order
Is there a simple/efficient way to do this? 有没有简单/有效的方法来做到这一点? Rather than writing blocks of if-else statements?
而不是编写if-else语句块?
I am trying to calculate the Friedman test ranks in Python. 我正在尝试计算Python中的Friedman测试等级。 Though there is a scipy.stats.friedmanchisquare function, it doesn't return the ranks The Friedman test
尽管有一个scipy.stats.friedmanchisquare函数,但它不会返回排名The Friedman test
EDIT 编辑
I have data like this in the Image 1 . 我在图像1中有这样的数据。
I tried comparing the values by using if else loops like this 我尝试通过使用if else循环来比较值
for i in range(0,10):
if(acc1[i]>acc2[i]):
if(acc1[i]>acc3[i]):
rank1[i] = 1
if(acc2[i]>acc3[i]):
rank2[i] = 2
rank3[i] = 3
friedmanchisquare
uses scipy.stats.rankdata
. friedmanchisquare
使用scipy.stats.rankdata
。 Here's one way you could use rankdata
with your three lists. 这是将
rankdata
与三个列表一起使用的一种方法。 It creates a list called ranks
, where ranks[i]
is an array containing the ranking of [a1[i], a2[i], a3[i]]
. 它创建一个名为
ranks
的列表,其中ranks[i]
是包含[a1[i], a2[i], a3[i]]
的排名的数组。
In [41]: a1
Out[41]: [1.0, 2.4, 5.0, 6]
In [42]: a2
Out[42]: [9.0, 5.0, 4, 5.0]
In [43]: a3
Out[43]: [5.0, 6.0, 7.0, 2.0]
In [44]: from scipy.stats import rankdata
In [45]: ranks = [rankdata(row) for row in zip(a1, a2, a3)]
In [46]: ranks
Out[46]:
[array([ 1., 3., 2.]),
array([ 1., 2., 3.]),
array([ 2., 1., 3.]),
array([ 3., 2., 1.])]
If you convert that to a single numpy array, you can then easily work with either the rows or columns of ranks
: 如果转换到一个numpy的数组,然后你可以轻松地与任意的行或列的工作
ranks
:
In [47]: ranks = np.array(ranks)
In [48]: ranks
Out[48]:
array([[ 1., 3., 2.],
[ 1., 2., 3.],
[ 2., 1., 3.],
[ 3., 2., 1.]])
In [49]: ranks.sum(axis=0)
Out[49]: array([ 7., 8., 9.])
You could define a simple function that returns the order of the sorts: 您可以定义一个简单的函数来返回排序顺序:
def sort3(a,b,c):
if (a >= b):
if (b >= c):
return (1, 2, 3)
elif (a >= c):
return (1, 3, 2)
else:
return (3, 1, 2)
elif (b >= c):
if (c >= a):
return (2, 3, 1)
else:
return (2, 1, 3)
else:
return (3, 2, 1)
Or consider using this https://stackoverflow.com/a/3382369/3224664 或考虑使用此https://stackoverflow.com/a/3382369/3224664
def argsort(seq):
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted(range(len(seq)), key=seq.__getitem__)
a = [1,3,5,7]
b = [2,2,2,6]
c = [3,1,4,8]
for i in range(len(a)):
print(argsort([a[i],b[i],c[i]]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.