Reputation: 503
I do some calculations with two 2D array with two for loop.
The answer I got are several seperate numbers.
Is there any method that I can turn the answers into one 2D array? Like this:
[[6.0, 10.9], [24.0, 33.8]]
This is my code:
import numpy as np
for i in range(1, 3):
arr2d_1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2d_2 = np.array([[2, 2, 2], [2, 2, 2]])
for j in range(0,2):
res = (arr2d_1*i+arr2d_2*j)/arr2d_1*i
sum_res = np.sum(res)
print(sum_res)
This is the result:
6.0
10.900000000000002
24.0
33.8
Upvotes: 1
Views: 88
Reputation: 2498
Yep so in this particular solution you could start by building a 2d array with zeroes, and fill up each element with the relevant calculation
results = np.zeros([2,2])
for i in range(1, 3):
arr2d_1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2d_2 = np.array([[2, 2, 2], [2, 2, 2]])
for j in range(0,2):
res = (arr2d_1*i+arr2d_2*j)/arr2d_1*i
sum_res = np.sum(res)
results[i-1,j] = sum_res
results
->
array([[ 6. , 10.9],
[24. , 33.8]])
But more broadly you can use np.reshape() to get arrays how you like them.
array = np.array([1,2,3,4)
array.reshape(2,2)
->
array([[1, 2],
[3, 4]])
Upvotes: 1
Reputation: 17322
just use:
import numpy as np
result = []
for i in range(1, 3):
arr2d_1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2d_2 = np.array([[2, 2, 2], [2, 2, 2]])
r = []
for j in range(0,2):
res = (arr2d_1*i+arr2d_2*j)/arr2d_1*i
sum_res = np.sum(res)
r.append(sum_res)
result.append(r)
print(result) # or np.array(result)
output:
[[6.0, 10.900000000000002], [24.0, 33.8]]
you are storing the intermediary results from each full inner for
loop iteration in a new list for each outer iteration
Upvotes: 1