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]]
CodePudding user response:
One option is to use np.hstack inside a list comprehension to stack each pair of tuples and then cast the resulting list to np.array:
a = np.array([np.hstack(tpl) for tpl in itertools.product(utl, all_ltp)])
Another option is to separate the np.arrays and tuples (from itertools.product) and vertically stack each to create two np.ndarray objects and then horizontally stack them.
a = np.array(list(itertools.product(utl, all_ltp)), dtype=object).T
a = np.hstack((np.vstack(a[0]), np.vstack(a[1])))
Output:
[[ 3. 12. 99. 0. 134.30000305]
[ 3. 12. 99. 1. 133.80000305]
[ 3. 17. 99. 0. 134.30000305]
[ 3. 17. 99. 1. 133.80000305]]
CodePudding user response:
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))))
