Reputation: 167
I have the following code:
ID= # type is <class 'str'>
dictionary={} #Dictionary
with open('result.PRED', 'a') as fileOut:
for item in dictionary.keys():
print(Question_ID,item,dictionary[item],sep='\t',file=fileOut)
which generates the following results from my document ranking model:
Q1_R1 Q1_R1_C1 0.0
Q1_R1 Q1_R1_C10 0.0
Q1_R1 Q1_R1_C2 0.0
Q1_R1 Q1_R1_C3 0.196116135138
Q1_R1 Q1_R1_C4 0.353553390593
Q1_R1 Q1_R1_C5 0.205267008777
Q1_R1 Q1_R1_C6 0.408248290464
Q1_R1 Q1_R1_C7 0.0
Q1_R1 Q1_R1_C8 0.0
Q1_R1 Q1_R1_C9 0.0
Q1_R6 Q1_R6_C1 0.301637573861
Q1_R6 Q1_R6_C10 0.199260956948
Q1_R6 Q1_R6_C2 0.147292928305
Q1_R6 Q1_R6_C3 0.0860264946736
Q1_R6 Q1_R6_C4 0.0819313340205
Q1_R6 Q1_R6_C5 0.244377512197
Q1_R6 Q1_R6_C6 0.161126919432
Q1_R6 Q1_R6_C7 0.152303771019
Q1_R6 Q1_R6_C8 0.0
Q1_R6 Q1_R6_C9 0.0
I need to create an additional column which is a rank based on the score given in column 3. Also, the second column is not properly sorted, as C10 appears before C2.
For example, I am trying to get as follows;
Q1_R1 Q1_R1_C1 0.0 4
Q1_R1 Q1_R1_C2 0.0 5
Q1_R1 Q1_R1_C3 0.196116135138 3
Q1_R1 Q1_R1_C4 0.353553390593 1
Q1_R1 Q1_R1_C5 0.205267008777 2
..... ..... .... ....
Q1_R1 Q1_R1_C10 0.0 6
I have been trying for a long time with various ways, and I could not find a way to handle this.Thanks
Upvotes: 1
Views: 63
Reputation: 11477
I use your output string as input data, use split()
method to get the list and sort it by third item, and then sort the list once again by multiple keys , here is the code:
r="""Q1_R1 Q1_R1_C1 0.0
Q1_R1 Q1_R1_C10 0.0
...
Q1_R6 Q1_R6_C6 0.161126919432
Q1_R6 Q1_R6_C7 0.152303771019
Q1_R6 Q1_R6_C8 0.0
Q1_R6 Q1_R6_C9 0.0"""
l=[i.split(' ') for i in r.split('\n')]
tmp=sorted(l,key=lambda x:float(x[2]),reverse=True)
for i in sorted([j+[i+1] for i,j in enumerate(tmp)],key=lambda x:(x[0],int(x[1].split('C')[-1]))):
print("\t".join(map(str,i)))
Result:
Q1_R1 Q1_R1_C1 0.0 13
Q1_R1 Q1_R1_C2 0.0 15
Q1_R1 Q1_R1_C3 0.196116135138 7
Q1_R1 Q1_R1_C4 0.353553390593 2
Q1_R1 Q1_R1_C5 0.205267008777 5
Q1_R1 Q1_R1_C6 0.408248290464 1
Q1_R1 Q1_R1_C7 0.0 16
Q1_R1 Q1_R1_C8 0.0 17
Q1_R1 Q1_R1_C9 0.0 18
Q1_R1 Q1_R1_C10 0.0 14
Q1_R6 Q1_R6_C1 0.301637573861 3
Q1_R6 Q1_R6_C2 0.147292928305 10
Q1_R6 Q1_R6_C3 0.0860264946736 11
Q1_R6 Q1_R6_C4 0.0819313340205 12
Q1_R6 Q1_R6_C5 0.244377512197 4
Q1_R6 Q1_R6_C6 0.161126919432 8
Q1_R6 Q1_R6_C7 0.152303771019 9
Q1_R6 Q1_R6_C8 0.0 19
Q1_R6 Q1_R6_C9 0.0 20
Q1_R6 Q1_R6_C10 0.199260956948 6
Upvotes: 1