将数字行与列表中的所有元素相乘 [英] multiply numpy row with all elements in list

查看:34
本文介绍了将数字行与列表中的所有元素相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Numpy数组中的所有行与列表元素相乘,如数组中的第一行与列表中的第一个元组、第二行与第二个元组等等。

我正在做此操作

utl  = np.array([[  3,         12.      ],
                 [  3.    ,  17.        ]])

all_ltp = ([(0, 134.30000305175778), (1, 133.80000305175778)])

a=np.array(list(itertools.product(utl, all_ltp)))
a = np.reshape(a, (-1,4))
print(a)

output is  - 
[[  3.          12.           0.         134.30000305]
 [  3.          12.           1.         133.80000305]
 [  3.          17.           0.         134.30000305]
 [  3.          17.           1.         133.80000305]]



它只起作用,但如果我增加数组的值,则

utl  = np.array([[  3,         12.  , 99   ],
                 [  3.    ,  17.   , 99    ]])

all_ltp = ([(0, 134.30000305175778), (1, 133.80000305175778)])

a=np.array(list(itertools.product(utl, all_ltp)))
a = np.reshape(a, (-1,2))
print(a)

output is - 

[[array([ 3., 12., 99.]) (0, 134.30000305175778)]
 [array([ 3., 12., 99.]) (1, 133.80000305175778)]
 [array([ 3., 17., 99.]) (0, 134.30000305175778)]
 [array([ 3., 17., 99.]) (1, 133.80000305175778)]]

它也在工作,但没有合并元素

output must be -

[[  3.          12.     99      0.         134.30000305]
 [  3.          12.     99      1.         133.80000305]
 [  3.          17.     99      0.         134.30000305]
 [  3.          17.     99      1.         133.80000305]]


推荐答案

首先将ALL_LTP转换为数组:

b = np.array(all_ltp)

然后通过重复utl和平铺b生成2个中间数组:

wrk1 = np.repeat(utl, repeats=b.shape[0], axis=0)
wrk2 = np.tile(b, reps=(utl.shape[0], 1))

(同时打印两者以查看结果)。

要获得最终结果,请水平堆叠这两个表:

result = np.hstack((wrk1, wrk2))

源数据的结果为:

[[  3.          12.          99.           0.         134.30000305]
 [  3.          12.          99.           1.         133.80000305]
 [  3.          17.          99.           0.         134.30000305]
 [  3.          17.          99.           1.         133.80000305]]

或者,更简洁的代码,运行:

result = np.hstack((np.repeat(utl, repeats=b.shape[0], axis=0),
    np.tile(b, reps=(utl.shape[0], 1))))

这篇关于将数字行与列表中的所有元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆