2

I want to mutiply this array of arrays with 1080 and 1920.

[[0.4375, 0.3477366255144033], [0.3599537037037037, 0.676954732510288], [0.5648148148148148, 0.720164609053498], [0.8483796296296297, 0.44238683127572015], [0.8726851851851852, 0.3374485596707819]]

So 0.4375 * 1080 and 0.3477 * 1920

I want to do this for each element.

How can I do this with Python or numpy?

petezurich
  • 9,280
  • 9
  • 43
  • 57
otto
  • 1,815
  • 7
  • 37
  • 63

4 Answers4

5

Just convert your data to arrays and then simply take a product *. The trick here is to create a 1-d vector of your two values with which you want to multiply. The * then performs element wise multiplication

import numpy as np

mult = np.array([1080, 1920])
inp = np.array([[0.4375, 0.3477366255144033], [0.3599537037037037, 0.676954732510288], 
                [0.5648148148148148, 0.720164609053498], [0.8483796296296297, 0.44238683127572015], 
                [0.8726851851851852, 0.3374485596707819]])

result = inp*mult
# array([[ 472.5       ,  667.65432099],
#        [ 388.75      , 1299.75308642],
#        [ 610.        , 1382.71604938],
#        [ 916.25      ,  849.38271605],
#        [ 942.5       ,  647.90123457]])

EDIT:: Time comparison Both methods work similarly

%timeit inp*mult
# 2.89 µs ± 365 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.multiply(inp, mult)
# 2.55 µs ± 322 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Sheldore
  • 37,862
  • 7
  • 57
  • 71
2

You want to perform element-wise multiplication of arrays. So use numpy.multiply() method.

>>> x1 = np.array([[0.4375, 0.3477366255144033], [0.3599537037037037, 0.676954732510288], [0.5648148148148148, 0.720164609053498], [0.8483796296296297, 0.44238683127572015], [0.8726851851851852, 0.3374485596707819]])
>>>
>>> x1
array([[0.4375    , 0.34773663],
       [0.3599537 , 0.67695473],
       [0.56481481, 0.72016461],
       [0.84837963, 0.44238683],
       [0.87268519, 0.33744856]])
>>> x2 = np.array([1080, 1920])
>>> x2
array([1080, 1920])
>>> prod = np.multiply(x1, x2)
>>> prod
array([[ 472.5       ,  667.65432099],
       [ 388.75      , 1299.75308642],
       [ 610.        , 1382.71604938],
       [ 916.25      ,  849.38271605],
       [ 942.5       ,  647.90123457]])

EDIT: As answered by @Sheldore above, using * operator is fine too, and does the same job.

Supratim Haldar
  • 2,376
  • 3
  • 16
  • 26
2

Just to provide a non numpy solution as an option since you said python or numpy you can do this easily with a simple for loop as well.

# myList is your list
for index in range(len(myList)):
    myList[index][0] *= 1080
    myList[index][1] *= 1920
print(myList)
1

Without numpy, you can use a list comprehension:

result = [ [a*1080,b*1920] for a,b in arrays ]

To handle any number of multipliers, you can use zip

multipliers = [1080,1920]
result = [ [a*m for a,m in zip(row,multipliers)] for row in arrays ]
Alain T.
  • 40,517
  • 4
  • 31
  • 51