我是 R 程式員,但需要使用 python 在表格中實作排名。假設我有一列“測驗”,其中包含數字串列:
df = pd.DataFrame({"test":[[1,4,7], [4,2,6], [3,8,1]]})
我希望跨行(串列)對同一位置的每個專案進行排名,并對所有排名進行平均以獲得最終分數:
預期的:
test rank_list final_score
0 [1, 4, 7] [1, 2, 3] 2
1 [4, 2, 6] [3, 1, 2] 2
2 [3, 8, 1] [2, 3, 1] 2
我知道所有最終分數都相同并不是一個很好的例子,但是如果有數百行,結果會是多種多樣的。我希望我能清楚地描述問題,但如果沒有,請隨時提問。
我不知道我是否可以在 pandas 中做到這一點,但我嘗試了 zip scipy,但scipy.stats.rankdata 沒有給出同一索引中專案的排名:
l = list(dff["test"])
ranks_list = [scipy.stats.rankdata(x) for x in zip(*l)] # not right
estimated_rank = [sum(x) / len(x) for x in ranks_list]
我對任何型別的包裹持開放態度,以方便為準。謝謝!
uj5u.com熱心網友回復:
import numpy as np
# Create a numpy array
a = np.array([[1,4,7], [4,2,6], [3,8,1]])
# get the index of the sorted array along each row
# Python uses zero-based indexing so we add 1
rank_list = np.argsort(a, axis=0) 1
# calculate the average rank of each column
final_score = np.mean(rank_list, axis=1)
uj5u.com熱心網友回復:
您可以使用rank方法來獲得排名。然后使用agg將輸出作為 column 的串列rank_list。最后,mean對于final_score:
tmp = pd.DataFrame(df['test'].tolist()).apply('rank').astype(int)
df['rank_list'] = tmp.agg(list, axis=1)
df['final_score'] = tmp.mean(axis=1)
輸出:
test rank_list final_score
0 [1, 4, 7] [1, 2, 3] 2.0
1 [4, 2, 6] [3, 1, 2] 2.0
2 [3, 8, 1] [2, 3, 1] 2.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449877.html
上一篇:用特定形式重塑陣列
