numpy 使用for循环添加两个数组

t1rydlwq  于 2022-12-23  发布在  其他
关注(0)|答案(6)|浏览(245)
from numpy import *
arr1 = array([5,10,15,20,30])
arr2 = array([55,16,1,280,60])
arr3 = ([])
k =0
for num1 in arr1:
    num3 = num1 + arr2[k]
    arr3.append(num3)
    k +=1
print(arr3)

如果arr1arr2有更多的索引怎么办?我该如何解决这个问题?

vyswwuz2

vyswwuz21#

from package import *通常不是个好主意,因为你可以覆盖你命名空间中的其他包。Numpy有一个内置的解决方案,可以将两个数组加在一起:

import numpy as np
arr1 = np.array([5,10,15,20,30])
arr2 = np.array([55,16,1,280,60])
arr1+arr2

array([ 60, 26, 16, 300, 90]) # 435 ns ± 5.89 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
但是,您需要两个数组具有相同的长度。
如果你想使用一些标准的python函数(而不是for循环),你可以使用mapzip来处理长度不同的数组:
list(map(sum, zip(arr1,arr2)))
[60, 26, 16, 300, 90] # 4.45 µs ± 60.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
如果你想使用for循环,你可以这样做:

new_list = []
for i in range(min(len(arr1), len(arr2))):
    new_list.append(arr1[i]+arr2[i])
new_list

[60, 26, 16, 300, 90] # 2.71 µs ± 307 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)所有这些都假设您希望在到达最短列表的末尾时停止。

4ngedf3f

4ngedf3f2#

如果数组的长度不等,首先需要对齐长度相同的部分,执行运算(例如加法),然后连接较长数组的剩余部分(可能应用其他运算,但本例中没有)。

import numpy as np

arr1 = np.array([5,10,15,20,30])
arr2 = np.array([55,16,1,280,60, 70])  # Longer than arr1.

min_len = min(len(arr1), len(arr2))
longer_array = arr1 if len(arr1) > len(arr2) else arr2
partial_result = arr1[:min_len] + arr2[:min_len]
>>> np.concatenate((partial_result, longer_array[min_len:]))
array([ 60,  26,  16, 300,  90,  70])
whitzsjs

whitzsjs3#

只需将最大的数组复制到新数组中,并将新数组的每个索引替换为两个数组各自索引的和,这样就可以避免索引越界和将较大数组的数组复制到新数组中。

from numpy import *

arr1 = array([1, 2, 3, 4, 5 ])
arr2 = array([6, 7, 8, 9, 10, 11, 12])
arr3 = ([])

if len(arr1) == len(arr2):  # Finding minimum length array
    minLength = len(arr1)
    pass
elif len(arr1) > len(arr2):
    minLength = len(arr2)
    arr3 = arr1.copy()     # Copy max array into new array
else:
    minLength = len(arr1)
    arr3 = arr2.copy()     # Copy max array into new array

for i in range(minLength):
    arr3[i] = arr1[i] + arr2[i]  # adding array and replacing in new array

print(arr3)
kpbpu008

kpbpu0084#

from numpy import *

arr1 = array([2, 6, 8, 9, 1])
arr2 = array([1, 2, 3, 4, 5])
list1 = [ ] 
e = 0
for num1 in arr1:
      list1.append(arr2[e] + num1)
      e+=1

print(array(list1))
s8vozzvw

s8vozzvw5#

#import numpy methods
from numpy import *

#initialize two array
arr1 = array([2, 6, 8, 1, 3])
arr2 = array([1, 6, 2, 1, 5])

#declare an empty array
arr3=([])

#find length of first array
n=len(arr1)

#traverse using for loop
for i in range(0,n):
        #append sum of both array in final array
        arr3.append(arr1[i]+arr2[i])

#print final array
print(arr3)
vqlkdk9b

vqlkdk9b6#

为此,我们需要首先导入numpy包,只有当两个数组长度相同时才使用此选项。

from numpy import*

arr1 = array([1,2,3,4,5])
arr2 = array([2,3,4,5,6])
for i in range(len(arr1)):
    arr3 = arr1[i] + arr2[i]
    print(arr3)

相关问题