繁体   English   中英

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

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

我有一个名为k的多维 numpy 数组。 每行代表变量,我有公式

我怎样才能拥有一个 numpy 数组,其中每一行(取决于列数,这只是一个示例)都已通过此公式处理?

我想要的 output 是这样的:

或者

[[12][12][4]]

您可以使用 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)

由于这些是 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:

[12. 12.  4.]

把它放在 function 中:

def function(m):
    x, y, z = m.transpose()
    return (4*z)/(x-y)

如果你想把它作为一个数组中的 3 个单项 arrays,把这个reshape作为 function 的最后一部分:

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

Output:

[[12.]
 [12.]
 [ 4.]]

你可以试试这个:

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