【问题标题】:Numpy function operating on two ndarrays在两个 ndarray 上运行的 Numpy 函数
【发布时间】:2019-09-14 00:32:23
【问题描述】:

给定两个 ndarrays a = np.asarray([[0,1,2],[3,4,5]])b = np.asarray([[6,7,8],[9,10,11]])我想写一个迭代 a 和 b 的函数,这样

  1. 考虑[0,1,2]和[6,7,8]
  2. 考虑 [3,4,5] 和 [9,10,11]

一个例子是一个函数,它需要

  1. [0,1,2]和[6,7,8]作为输入输出0*6+1*7+2*8 = 23
  2. [3,4,5] 和 [9,10,11] 作为输入输出 3*9+4*10+5*11 = 122

-> (23,122)

有没有办法在 numpy 中有效地做到这一点? 我的想法是压缩两个数组,但是效率不高。

编辑:我正在寻找一种方法来应用可自定义的函数myfunc(x,y)。在前面的例子中,myfunc(x,y) 对应于乘法。

【问题讨论】:

  • 做 hadamard 产品然后沿axis=1求和:np.sum(a*b,axis=1)

标签: python numpy


【解决方案1】:
c = a * b 
sum1 = c[0].sum()
sum2 = c[1].sum() 

如果你想要算法方式(自定义函数)

a = np.asarray([[0,1,2],[3,4,5]])
b = np.asarray([[6,7,8],[9,10,11]])


for i in range(a.shape[0]) : 
  s = 0
  for j in range(a.shape[1]) :
    s = s + a[i][j]*b[i][j]
  print(s)

【讨论】:

    【解决方案2】:


    将 numpy 导入为 np a = np.asarray([[0,1,2],[3,4,5]]) b = np.asarray([[6,7,8],[9,10,11]]) c = a*b 打印(总和(c[0]),总和(c1)) 答案->23,122

    【讨论】:

      【解决方案3】:

      不需要同时使用 zip 数组,您需要了解 numpy 包帮助您很好地使用矩阵。所以你需要矩阵的基本知识,我建议你从这个链接学习http://cs231n.github.io/python-numpy-tutorial/,来自斯坦福大学的cs231n。 这是一个可以解决你问题的函数:

       import numpy as np
       def interates(matrix_a, matrix_b):
          product = matrix_a*matrix_b
          return (np.sum(product,1))
      

      值积包含一个新矩阵,matrix_a和matrix_b形状相同,其中每个元素都是matrix_a[i][j] * matrix_b[i][j]的结果,i和j从0到matrix_a.shape[0]matrix_a.shape[1]

      现在看看你的例子

      a = np.asarray([[0,1,2],[3,4,5]])
      b = np.asarray([[6,7,8],[9,10,11]])
      result = interates(a,b)
      

      打印结果

      >> print(result)
      >> [23 122]
      

      如果你想要一个元组

      >> result = tuple(result)
      >> print(result)
      >> (23, 122)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-05
        • 2022-09-23
        • 2018-12-24
        • 2021-10-15
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        相关资源
        最近更新 更多