Trying to calculate the ranks for Spearmen's correlation

19 Views Asked by At

I am trying to calculate the Spearmen's ranking for correlation manually with functions in Python, however I am having an issue with the equality area. Would any be able to help me?

My plan is to create a function that receives list then calculates the ranks, with one function that confirms if the list has unique values or not, then using a separate function that provides the ranking for duplicate values specifically.

Below is my code:

#Calculating the Spearman's correlation

#Calculating the ranks
list_maths = df['Maths'].tolist()
list_science = df['Science'].tolist()

def calculate_ranks(array):
  sorted_index = list(sorted(range(len(array)), key=lambda k: array[k], reverse=True))
  rank_array = [x+1 for x in sorted_index]
  if checkIfArrayIsUnique==False:
    return rank_array
  else:
    for x in array:
      index = array.index(x)
      for y in array:
        temp_index = array.index(y)
        if index !=(temp_index):
          if x is y: 
            duplicate_rank = return_duplicate_rank(array, rank_array, y)
            rank_array.insert(index, duplicate_rank)
    return rank_array

def return_duplicate_rank(array,ranked_array,duplicate):
  count = 0
  duplicate_ranks = []
  for x in array:
    if duplicate==x:
      index = array.index(duplicate)
      duplicate_ranks.append(ranked_array.index(duplicate))
      count = count + 1
  duplicate_ranks = duplicate_ranks.sort()
  duplicate_rank = (duplicate_ranks[-1]/count)
  return duplicate_rank


def checkIfArrayIsUnique(array):
  i = 0
  for x in array:
    index = array.index(x)
    for y in array:
      temp_index = array.index(y)
      if index !=(temp_index): #looks like the error is here 
        print('works')
        if x == y:
          print('works')
          return True
        else:
          continue
      else:
        continue
  return False

try_list = [1,2,2,3,4,5]
print(calculate_ranks(try_list))
0

There are 0 best solutions below