简体   繁体   中英

Sum numpy array values based on labels in a separate array

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.

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM