[英]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: 这是我的numpy数组:
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: 我需要将数组第二行中的值乘以
ls
中列表的长度,该长度在第一行中对应数字的索引处 :
10 * len(ls[1])
& 100 * len(ls[0])
etc.. 10 * len(ls[1])
和100 * len(ls[0])
等。
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: 使用
list comprehesion
找到长度并将其乘以数组的第二行,如下所示:
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.