0

I need help for my code. I have two arrays, one obtained randomly.

For example: Let’s say the two arrays are:

randm and r_q

randm = [1 0 1]
r_q = [[3 5 2]
       [5 4 3]
       [5 2 2]]

By multiplying the values above and transposing its product, I got:

multi_trans_output =   [[3 0 5]
                        [5 0 2]
                        [2 0 2]]

What I need to do now is to store the values in multi_trans_output into another arrays like:

r1 = [3 0 5]
r2 = [5 0 2]
r3 = [2 0 2]

Then get their sums:

r1_sum = [8]
r2_sum = [7]
r3_sum = [4]

So far, my code looks like this:

multi_trans_output = populations*r_q_active.T
# loop for storing of values in r(x)
for d in multiplied_output:
.
.
print(r(x))
r(x)_sum = numpy.sum(r(x), axis=1)

Any help/suggestion would be very much appreciated! Thanks in advance.

4
  • If the size of the arrays are big, I recommand to use pandas. These are standard transformations for this module. Commented Jun 2, 2020 at 11:21
  • you want something like this np.sum(randm*r_q.T,axis=1)? Commented Jun 2, 2020 at 11:35
  • @ShubhamShaswat I want to store the values in multi_trans_output into another array r[i] based on its index. As an example, r1 = multi_trans_output[1]. Afterwards, I will get the sum of the values in r1 and store it in r1_sum. Commented Jun 2, 2020 at 11:51
  • @pyOliv I am still new to Python. So far, my searches almost always used numpy that is why I chose it for this code. Commented Jun 2, 2020 at 11:53

1 Answer 1

1

You can store each rows in a dictionary with their respective name as keys

import numpy as np 

# input two matrices 
randm = np.array([1,0,1])
r_q = np.array([[3, 5, 2],[5, 4, 3],[5, 2, 2]])
# This will return dot product 
res = randm*r_q.T


# print resulted matrix
dic_for_arrays = {}
dic_for_sum  = {}
for index,lst in enumerate(res):
    dic_for_arrays['row'+str(index+1)] = lst
    dic_for_sum['row'+str(index+1)] = np.sum(lst)
for i in dic_for_arrays:
    print(f"{i} = {dic_for_arrays[i]} \nsum of {i} = {dic_for_sum[i]}")


# Output:
row1 = [3 0 5] 
sum of row1 = 8
row2 = [5 0 2] 
sum of row2 = 7
row3 = [2 0 2] 
sum of row3 = 4
Sign up to request clarification or add additional context in comments.

1 Comment

I tried running this code and it worked perfectly! Thank you so much for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.