如何创建一个 numpy 二维数组,其元素取决于两个已固定列表的元素
How to create a numpy 2-D array whose elements depend on elements of two lists already fixed
示例:
让
A = np.array([1,2,3,5,7])
B = np.array([11,13,17,19,23])
我想创建一个大小为 (5,5)
的矩阵 C
,其元素为
c_ij = f(a[i],b[j])
其中 f
是固定函数,例如 f(x,y) = x*y + x + y
表示
c_ij = a[i]*b[j] + a[i] + b[j]
在 c_ij
仅依赖于 i
和 j
而不依赖于列表 A
和 B
的情况下,我们可以使用np.fromfunction(lambda i,j: f(i,j), (5,5))
但事实并非如此
我想知道我们该怎么做?
import numpy as np
# set up f()
def _my_math_function(x, y):
return x*y + x + y
# variable setup
A = np.array([1,2,3,5,7])
B = np.array([11,13,17,19,23])
# nested comprehensive loop
# basically f(1,11), (1,13) ... f(7,19) f(7,23)
c = [_my_math_function(a,b) for b in B for a in A]
# len list
shape_a = len(A)
shape_b = len(B)
c = np.array(c).reshape(shape_a,shape_b)
# Results of c
array([[ 23, 35, 47, 71, 95],
[ 27, 41, 55, 83, 111],
[ 35, 53, 71, 107, 143],
[ 39, 59, 79, 119, 159],
[ 47, 71, 95, 143, 191]])
这是你想要的吗:
def bar(arr1, arr2, func):
ind1, ind2 = np.meshgrid(range(len(arr1)), range(len(arr2)))
x = arr1[ind1]
y = arr2[ind2]
return func(x, y)
bar(A, B, f)
示例:
让
A = np.array([1,2,3,5,7])
B = np.array([11,13,17,19,23])
我想创建一个大小为 (5,5)
的矩阵 C
,其元素为
c_ij = f(a[i],b[j])
其中 f
是固定函数,例如 f(x,y) = x*y + x + y
表示
c_ij = a[i]*b[j] + a[i] + b[j]
在 c_ij
仅依赖于 i
和 j
而不依赖于列表 A
和 B
的情况下,我们可以使用np.fromfunction(lambda i,j: f(i,j), (5,5))
但事实并非如此
我想知道我们该怎么做?
import numpy as np
# set up f()
def _my_math_function(x, y):
return x*y + x + y
# variable setup
A = np.array([1,2,3,5,7])
B = np.array([11,13,17,19,23])
# nested comprehensive loop
# basically f(1,11), (1,13) ... f(7,19) f(7,23)
c = [_my_math_function(a,b) for b in B for a in A]
# len list
shape_a = len(A)
shape_b = len(B)
c = np.array(c).reshape(shape_a,shape_b)
# Results of c
array([[ 23, 35, 47, 71, 95],
[ 27, 41, 55, 83, 111],
[ 35, 53, 71, 107, 143],
[ 39, 59, 79, 119, 159],
[ 47, 71, 95, 143, 191]])
这是你想要的吗:
def bar(arr1, arr2, func):
ind1, ind2 = np.meshgrid(range(len(arr1)), range(len(arr2)))
x = arr1[ind1]
y = arr2[ind2]
return func(x, y)
bar(A, B, f)