I have a multidimensional numpy array called k
. Each row represents variables and i have the formula
How can I have a numpy array where every row (depending of the number of columns, this is just an example) has been processed by this formula?
My desired output is something like this:
or
[[12][12][4]]
You could use apply_along_axis.
import numpy as np
k = [[4, 2, 6], [5, 2, 9], [10, 3, 7]]
k = np.array(k)
def function(m):
x = m[0]
y = m[1]
z = m[2]
return ((4*z)/(x-y))
result = np.apply_along_axis(function, 1, k)
print(result)
Since these are numpy arrays, you can use array operations to solve all of these together without needing loops:
import numpy as np
k = [[4, 2, 6], [5, 2, 9], [10, 3, 7]]
k = np.array(k)
t = k.transpose()
x, y, z = t
print((4*z)/(x-y))
Output:
[12. 12. 4.]
Putting that in a function:
def function(m):
x, y, z = m.transpose()
return (4*z)/(x-y)
And if you want it as 3 single-item arrays in an array, put this reshape
as the last part of the function:
a = (4*z)/(x-y)
print(a.reshape(3, 1))
Output:
[[12.]
[12.]
[ 4.]]
you can try this:
import numpy as np
# [(x1, y1, z1), (x2, y2, z2) ...)]
k = [[4, 2, 6], [5, 2, 9], [10, 3, 7]]
k = np.asarray(k)
x = k[:, 0]
y = k[:, 1]
z = k[:, 2]
out = np.divide(4*z, x-y)
# out = (4*z) / (x-y)
print(out)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.