0

I tried calculating the sum of each column in a 2D array O and stored it in 1D array col_sum. But I see my array O getting updated automatically after updating array col_sum. Not able to figure out why. Please help.

OUTPUT:

Row 1 of array O: Before [ 14 83 236 55 58 9 64]

Updated col_sum [ 20 117 463 126 112 29 133]

Row 1 of array O: After [ 20 117 463 126 112 29 133]

import numpy as np

O = np.array([[14,83,236,55,58,9,64],[6,34,227,71,54,20,69]])
print('Row 1 of array O: Before', O[0])

row, col = O.shape

col_sum = O[0] # PROBLEM AREA

for i in range(row):
    for j in range (col):
        if i>0:
            col_sum[j] = col_sum[j] + O[i][j] #PROBLEM AREA - Why is array O getting updated?
            
            
print ('Updated col_sum', col_sum)
print ('Row 1 of array O: After', O[0])

1 Answers1

0

You need to use col_sum = np.copy(O[0]) to ensure updates to col_sum are not also reflected in O.

Refer https://stackoverflow.com/a/19676762/11778344 for a detailed explanation.

S V Praveen
  • 421
  • 3
  • 8