我有两个二维数组,其中每行表示一个时间,每列表示一个项目。我想找出每个项目的两个数组之间的最大差异。(我并不特别关心在这一点上找出最大的差异。)
我想创建一个这些最大差异的列表,这样以后我就可以找到该列表中最大的15个。
到目前为止,我已经尝试通过做这样的事情来完成这项任务:
import numpy as np
array1 = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]]
array2 = [[6, 7, 8, 9, 10], [11, 22, 33, 44, 55], [1, 4, 9, 16, 25]]
num_items = np.shape(array1)[1]
num_timesteps = np.shape(array1)[0]
for counter in np.arange(0, num_items):
for counter2 in np.arange(0, num_timesteps):
diff_list = []
diff = array1[counter2][counter] - array2[counter2][counter]
diff = abs(diff)
diff_list.append(diff)
max_diff = []
max_diff.append(max(diff_list))
print max_diff
但是,这不会打印实际的列表。相反,它为我提供了每个项目的一个列表,其中该项目的差异最大。
期望输出:[2,2,0,4,10]
电流输出:[2][2][0][4][10]
所以,我的问题是:如何找到两个数组之间的最大差异,并将它们放在一个列表中?
为了获得所需的输出,您需要将max_diff = []
移到for循环之外。这将导致以下代码:
import numpy as np
array1 = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]]
array2 = [[6, 7, 8, 9, 10], [11, 22, 33, 44, 55], [1, 4, 9, 16, 25]]
num_items = np.shape(array1)[1]
num_timesteps = np.shape(array1)[0]
max_diff= [] #moves this outside of the for loop
for counter in np.arange(0, num_items):
for counter2 in np.arange(0, num_timesteps):
diff_list = []
diff = array1[counter2][counter] - array2[counter2][counter]
diff = abs(diff)
diff_list.append(diff)
max_diff.append(max(diff_list))
print (max_diff)
输出:[2,2,0,4,10]
使用np.subtract
怎么样?在创建循环迭代器时,您忽略了使用numpy的要点。
不能100%确定这是否有效,因为我没有安装numpy,但这里的代码:
import numpy as np
array1 = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]]
array2 = [[6, 7, 8, 9, 10], [11, 22, 33, 44, 55], [1, 4, 9, 16, 25]]
array1, array2 = np.asarray(array1), np.asarray(array2)
diff = np.subtrat(array1, array2)
diff = np.absolute(diff)
print diff.max()
通过列表压缩,您可以执行以下操作:
a=[abs(b-c) for x,y in zip(array1,array2) for b,c in zip(x,y)]
输出:[5,5,5,5,9,18,27,36,45,2,0,4,10]
编辑:你只想要最后一个所以:
a=[abs(x-y) for x,y in zip(array1[2],array2[2])]
输出:[2,2,0,4,10]
这比numpy操作慢一点,但对于这种大小,这应该不是问题。