multiply numpy row with all elements in list

Viewed 266

how to multiply all rows in numpy array with list elements one by one like first row in array with first tuple in list , second with second and so on.

i am doing this

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]]



it only works but if i increase the values of array then

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)]]

it is also working but not combining elements

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]]


1 Answers

First convert all_ltp to a Numpy array:

b = np.array(all_ltp)

Then generate 2 intermediate arrays, by repeating utl and tiling b:

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

(print both of them to see the result).

And to get the final result, horizontally stack both these tables:

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

The result, for your source data, is:

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

Or, to have more concise code, run:

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