I am trying two multiply two ore more different arrays with one constant factor. For example, I have two arrays from pressure measurement in bar and want to convert every array seperately to Pa by multiplying every row by the factor 1e5. The return should be also two arrays. I thought about a for loop, but I am new to Python and I have no idea how to deal with it.
# for example
import numpy as np
p1=np.array([2,3,4]) # pressure measurement p1 in bar
p2=np.array([8,7,6]) # pressure measurement p2 in bar
# loop to multiply p1 and p2 seperately with 1e5
# return
# p1[2e5,3e5,4e5]
# p2[8e5,7e5,6e5]
Can anybody help?
Thank you very much!
Jonas
CodePudding user response:
NumPy arrays support scalar multiplication (it's a special case of broadcasting). Just directly multiply the array by the constant: p1 *= 1e5
If you get a UFuncTypeError
, it means that your array datatype doesn't match the type of the constant multiplier. For example a = np.array([1,2,3])
will create an array with int32
datatype by default, and NumPy casting rules don't allow it to by multiplied by a float. To fix this, you can explicitly specify the datatype: a = np.array([1,2,3], dtype=float)
or you can give the entries as floats: a = np.array([1.0,2.0,3.0])
CodePudding user response:
use numpy.multiply
for this
x = np.array([2,3,4])
y = np.multiply(x, 1e5)
print(y)
Output:
[200000. 300000. 400000.]
x
is not changed in the process
CodePudding user response:
def multiply_two_arrays(a1, a2, factor):
return a1*factor, a2*factor
a1, a2 = multiply_two_arrays(p1, p2, 10)