【发布时间】:2018-12-22 13:40:15
【问题描述】:
我有三个 NumPy 数组 整数,列数相同,行数任意。我对第一个的一行加上第二个的一行给出第三个的行的所有实例感兴趣([3, 1, 4] + [1, 5, 9] = [4, 6, 13 ])。
这是一个伪代码:
for i, j in rows(array1), rows(array2):
if i + j is in rows(array3):
somehow store the rows this occured at (eg. (1,2,5) if 1st row of
array1 + 2nd row of array2 give 5th row of array3)
我需要为非常大的矩阵运行这个,所以我有两个问题:
(1) 我可以使用嵌套循环编写上述内容,但是否有更快的方法,可能是 list comprehensions 或 itertools?
(2) 什么是最快/最节省内存的存储方式三元组?稍后我将需要创建一个热图,使用两个作为坐标,第一个作为相应的值,例如。在伪代码示例中,点 (2,5) 的值为 1。
非常感谢任何提示 - 我知道这听起来很简单,但它需要快速运行,而且我对优化的经验很少。
编辑:我的丑陋代码是在 cmets 中请求的
import numpy as np
#random arrays
A = np.array([[-1,0],[0,-1],[4,1], [-1,2]])
B = np.array([[1,2],[0,3],[3,1]])
C = np.array([[0,2],[2,3]])
#triples stored as numbers with 2 coordinates in a otherwise-zero matrix
output_matrix = np.zeros((B.shape[0], C.shape[0]), dtype = int)
for i in range(A.shape[0]):
for j in range(B.shape[0]):
for k in range(C.shape[0]):
if np.array_equal((A[i,] + B[j,]), C[k,]):
output_matrix[j, k] = i+1
print(output_matrix)
【问题讨论】:
-
分享您基于嵌套循环的工作解决方案以及最小样本?
-
列数总是很少吗?整数本身很小吗?您是否知道典型或最坏情况的行数?
-
@Divakar 代码已添加。
-
@EelcoHoogendoorn 这些数字大多非常小:-10
-
您确定该输出吗?那不应该是
N x 3数组吗?另外,我不相信存储i+1是否是所需的。
标签: python arrays numpy matrix optimization