I have a python question:
If I have a multidimensional array lets say shape (3,4) and a 1D array with 3 values that for example look like this:
profile = np.array([[1,2,3,5],[3,6,2,5],[2,8,3,5]])
radius = np.array([4,8,3])
I am looking for a way to divide all values from the first/second element of my multidimensional array by the corresponding first/second number of the 1D array. So as an output I would basically something like:
profile_new = np.array[[1,2,3,5]/4], [[3,6,2,5]/8], [[2,8,3,5]/3]
I tried:
for i,j in zip(radius_prof, r_500):
radius = i/j
But this yields an array only consisting of 4 elements, but I want again a multidimensional array with shape (3,4).
I hope my question is understandable, this is my first post here and I could not find any similar question.
Thanks in advance!
CodePudding user response:
You need to append
results to a list in for
:
import numpy as np
profile = np.array([[1,2,3,5],[3,6,2,5],[2,8,3,5]])
radius = np.array([4,8,3])
result = []
for i,j in zip(profile, radius):
result.append(i/j)
result
By list comprehension :
result = [x/y for x,y in zip(profile,radius) ]
A better way :
result = np.divide(profile.T, radius).T
Output:
[array([0.25, 0.5 , 0.75, 1.25]),
array([0.375, 0.75 , 0.25 , 0.625]),
array([0.66666667, 2.66666667, 1. , 1.66666667])]
CodePudding user response:
What about using simple division and broadcasting?
profile = np.array([[1,2,3,5],[3,6,2,5],[2,8,3,5]])
radius = np.array([4,8,3])
print(profile / radius[:, None])
# [[0.25 0.5 0.75 1.25 ]
# [0.375 0.75 0.25 0.625 ]
# [0.66666667 2.66666667 1. 1.66666667]]