简体   繁体   English

Numpy:对数组每行的元素应用公式

[英]Numpy: Applying a formula with elements of each row of an array

I have a multidimensional numpy array called k .我有一个名为k的多维 numpy 数组。 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?我怎样才能拥有一个 numpy 数组,其中每一行(取决于列数,这只是一个示例)都已通过此公式处理?

My desired output is something like this:我想要的 output 是这样的:

or或者

[[12][12][4]]

You could use apply_along_axis.您可以使用 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:由于这些是 numpy arrays,因此您可以使用数组运算来解决所有这些问题,而无需循环:

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: Output:

[12. 12.  4.]

Putting that in a function:把它放在 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:如果你想把它作为一个数组中的 3 个单项 arrays,把这个reshape作为 function 的最后一部分:

a = (4*z)/(x-y)
print(a.reshape(3, 1))

Output: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM