2

I have arrays similar to the following:

a=[["tennis","tennis","golf","federer","cricket"],
   ["federer","nadal","woods","sausage","federer"],
   ["sausage","lion","prawn","prawn","sausage"]]

I then have a matrix of the following weights

w=[[1,3,3,4,5],
   [2,3,2,3,4],
   [1,2,1,1,1]]

What I am looking to then do is to sum the weights based on the labels of matrix a for each row and take the top 3 labels from that row. So at the end I would like something like this:

res=[["cricket","tennis","federer"],
     ["federer","sausage","nadal"],
     ["lion","sausage","prawn"]]

In my actual data set ties would be highly unlikely and are not really a concern, also for cases where say the entire row is:

["federer","federer","federer","federer","federer"]

Ideally I would like this to be returned as ["federer","",""].

Any guidance would be appreciated.

3 Answers 3

3

See piRSquared answer for numpy arrays.

This is a pure python approach:

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)
Sign up to request clarification or add additional context in comments.

Comments

2

Try:

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

1 Comment

Actually does this choose based on the sum of the weights?
1

I managed to get it to work using below code:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.