我有类似以下的数组:
a=[["tennis","tennis","golf","federer","cricket"],
["federer","nadal","woods","sausage","federer"],
["sausage","lion","prawn","prawn","sausage"]]
然后我有一个以下权重的矩阵
w=[[1,3,3,4,5],
[2,3,2,3,4],
[1,2,1,1,1]]
我当时要做的是根据每行的矩阵a的标签对权重求和,并从该行中取出前3个标签。所以最后我想要这样的事情:
res=[["cricket","tennis","federer"],
["federer","sausage","nadal"],
["lion","sausage","prawn"]]
在我的实际数据集中,关系是非常不可能的,并不是真正的问题,也适用于整个行的情况:
["federer","federer","federer","federer","federer"]
理想情况下,我希望将此作为返回 [ “费德勒”, “”, “”]。
任何指导都将不胜感激。
答案 0 :(得分:3)
有关numpy数组的信息,请参阅piRSquared answer。
这是一种纯粹的python方法:
for i in range(4):
if a[i].count(a[i][0]) == len(a[i]):
res = [a[1][0], "", ""]
else:
res = [x[0] for x in sorted(zip(a[i], w[i]), key=lambda c: c[1], reverse=True)[:3]]
print(res)
答案 1 :(得分:2)
尝试:
print pd.DataFrame(
{i: a.loc[i, row.sort_values(ascending=False).index[:3]].values for i, row in w.iterrows()}
).T
0 1 2
0 cricket federer golf
1 federer sausage nadal
2 lion sausage prawn
答案 2 :(得分:1)
我设法使用以下代码让它工作:
def myf(a,w):
lookupTable, indexed_dataSet = np.unique(a, return_inverse=True)
y= np.bincount(indexed_dataSet,w)
lookupTable[y.argsort()]
res=(lookupTable[y.argsort()][::-1][:3])
ret=np.empty((3))
ret.fill(res[-1])
ret[0:res.shape[0]]=res
return ret
result = np.empty_like(knearest_labels[:,0:3])
for i,(x,y) in enumerate(zip(a,w)):
result[i] = myf(x,y)