Reputation: 907
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?
Upvotes: 0
Views: 76
Reputation: 13255
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]])
Upvotes: 3