如何从Python中的另一个元素中减去数组的所有元素?

时间:2014-07-10 11:45:11

标签: python for-loop numpy

我需要从数组x2中的所有数字中减去数组x1中的数字,并检查结果的绝对值是否小于0.01,如果是,则将x1附加到新数组。然后我需要这个来重复数组x1中的所有元素。

这样做需要250亿次计算,因为两个阵列都很长(50000和500000个元素),所以我更愿意尽量减少所需的处理量。

谢谢!

b = np.zeros(len(a), 1)               #a is a list of numbers 48555 elements long
b[:,0] = a[:,0]

e = np.zeros(len(d), 1)               #d is a list of numbers 531261 elements long
e[:,0] = d[:,0]

h = np.zeros(len(len(a)*len(d),1)     #h needs to be an array of length a*d
for i in e, j in b,
if abs(i-j)<=0.01,
h.append(i)

print h

我之前没有使用过很多代码,所以我仍然在用Python做出相当基本的错误。

1 个答案:

答案 0 :(得分:0)

x1 = np.array([5, 8, 3, 4, 5, 6])
x2 = np.array([ 0, 6, 3, 4, 2, 7])

print all(abs(np.subtract(x2 ,x1[1]) < .01))
True

print all(abs(np.subtract(x2 ,x1[0]) < .01))
False

你可以循环遍历x1并在任何值为&gt;时继续.01以避免检查所有值:

for ele in x1:
    if any(abs(x - ele) > .01 for x in x2 ):
        continue
    else: add your array
相关问题