简体   繁体   中英

Multiplying row in NumPy array by specific values based on another row

I have the following list:

ls = [[1,2,3], [3,4] , [5] , [7,8], [23], [90, 81]]

This is my numpy array:

array([[    1,     0,     4,     3],
       [   10,   100,  1000, 10000]])

I need to multiply the values in the second row of my array by the length of the list in ls which is at the index of the corresponding number in the first row:

10 * len(ls[1]) & 100 * len(ls[0]) etc..

The objective output would be this array:

array([[    1,     0,     4,     3],
       [   20,   300,  1000, 20000]])

Any efficient way doing this?

Use list comprehesion to find lengths and multiply it with 2nd row of array as:

ls = [[1,2,3], [3,4] , [5] , [7,8]]
arr = np.array([[    1,     0,     2,     3],
                [   10,   100,  1000, 10000]])

arr[1,:] = arr[1,:]*([len(l) for l in ls])

arr
array([[    1,     0,     2,     3],
       [   30,   200,  1000, 20000]])

EDIT :

arr[1,:] = arr[1,:]*([len(ls[l]) for l in arr[0,:]])

arr
array([[    1,     0,     2,     3],
       [   20,   300,  1000, 20000]])

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