numpy:将两个数组合并为一个矩阵,然后使用lambda进行映射

时间:2019-01-08 09:55:36

标签: python numpy

我想将两个numpy.ndarray(m, n)元素组合成一个m x n矩阵,然后应用一个函数/ lambda来映射值。

例如:

import numpy as np
X = np.array([1,2,3])
Y = np.array([4,5,6,7])
Z = cross_combine(X, Y)
# combine two arrays into a matrix containing the tuple (Xi, Yj)
# array([[(1,4), (1,5), (1,6), (1,7)],
#        [(2,4), (2,5), (2,6), (2,7)],
#        [(3,4), (3,5), (3,6), (3,7)]])

Z = Z.map(lambda x, y: x * y)
# map values with a lambda or a function
# array([[4, 5, 6, 7],
#        [8, 10, 12, 14],
#        [12, 15, 18, 21]])

映射功能将很复杂。 numpy中的cross_combinemap函数是什么?我如何轻松实现?

3 个答案:

答案 0 :(得分:2)

对于您的特定示例,您可以使用np.meshgridreduce

import numpy as np


def mesh(values):
    return np.array(np.meshgrid(*values)).T

X = [1,2,3]
Y = [4,5,6,7]

Z = mesh([X, Y])

result = np.multiply.reduce(Z, axis=2)
print(result)

输出

[[ 4  5  6  7]
 [ 8 10 12 14]
 [12 15 18 21]]

对于自定义功能,您可以使用np.frompyfunc

def_mult = np.frompyfunc(lambda x, y: x * y, 2, 1)
result = def_mult.reduce(Z, axis=2)
print(result)

输出

[[4 5 6 7]
 [8 10 12 14]
 [12 15 18 21]]

答案 1 :(得分:1)

您可以使用列表推导:

X = [1,2,3]
Y = [4,5,6,7]

在列表理解中使用itertools.product来获取两个列表的笛卡尔积,并保留指定的嵌套列表结构:

Z = [list(product([x],Y)) for x in X]
#[[(1, 4), (1, 5), (1, 6), (1, 7)],
# [(2, 4), (2, 5), (2, 6), (2, 7)],
# [(3, 4), (3, 5), (3, 6), (3, 7)]]

并使用嵌套列表组合来应用保留结构的函数:

[[x*y for x,y in z] for z in Z]
#[[4, 5, 6, 7], [8, 10, 12, 14], [12, 15, 18, 21]]

答案 2 :(得分:0)

您可以执行以下操作:

import numpy as np

X = [1, 2, 3]
Y = [4, 5, 6, 7]
Z = np.tensordot(X, Y, axes=0)
print(Z)
# [[ 4  5  6  7]
#  [ 8 10 12 14]
#  [12 15 18 21]]

对于其他操作,您可以执行以下操作:

import numpy as np

X = [1, 2, 3]
Y = [4, 5, 6, 7]
X2d = np.asarray(X)[:, np.newaxis]
Y2d = np.asarray(Y)[np.newaxis, :]

print(X2d * Y2d)
# [[ 4  5  6  7]
#  [ 8 10 12 14]
#  [12 15 18 21]]
print(X2d + Y2d)
# [[ 5  6  7  8]
#  [ 6  7  8  9]
#  [ 7  8  9 10]]
print(X2d ** Y2d)
# [[   1    1    1    1]
#  [  16   32   64  128]
#  [  81  243  729 2187]]

编辑:或者实际上只是:

import numpy as np

X = [1, 2, 3]
Y = [4, 5, 6, 7]

print(np.multiply.outer(X, Y))
# [[ 4  5  6  7]
#  [ 8 10 12 14]
#  [12 15 18 21]]
print(np.add.outer(X, Y))
# [[ 5  6  7  8]
#  [ 6  7  8  9]
#  [ 7  8  9 10]]
print(np.power.outer(X, Y))
# [[   1    1    1    1]
#  [  16   32   64  128]
#  [  81  243  729 2187]]