I am trying to do assignments to different variables in my code, but for some reason, the last one is being persistent. I have tracked the problem until the example below. If someone is able to explain this behavior it will be great.
import numpy as np
metric_a = metric_b = metric_c = metric_d= np.zeros(10)
j = 0
temp_a = 1
temp_b = 2
temp_c = 1
temp_d = 5
print('temp_a=', temp_a, ' temp_b=', temp_b, ' temp_c=', temp_c, ' temp_d=', temp_d)
print('metric_a[' str(j) ']=', metric_a[j], ' metric_b[' str(j) ']=', metric_b[j], ' metric_c[' str(j) ']=',metric_c[j], ' metric_d[' str(j) ']=',metric_d[j])
print('j:',j, '\n')
metric_a[j] = temp_a
metric_b[j] = temp_b
metric_c[j] = temp_c
metric_d[j] = temp_d
print('temp_a=', temp_a, ' temp_b=', temp_b, ' temp_c=', temp_c, ' temp_d=', temp_d)
print('metric_a[' str(j) ']=', metric_a[j], ' metric_b[' str(j) ']=', metric_b[j], ' metric_c[' str(j) ']=',metric_c[j], ' metric_d[' str(j) ']=',metric_d[j])
Here is the output
temp_a= 1 temp_b= 2 temp_c= 1 temp_d= 5
metric_a[0]= 0.0 metric_b[0]= 0.0 metric_c[0]= 0.0 metric_d[0]= 0.0
j: 0
temp_a= 1 temp_b= 2 temp_c= 1 temp_d= 5
metric_a[0]= 5.0 metric_b[0]= 5.0 metric_c[0]= 5.0 metric_d[0]= 5.0
When I have been waiting for
metric_a[0]= 1.0 metric_b[0]= 2.0 metric_c[0]= 1.0 metric_d[0]= 5.0
CodePudding user response:
You can do that with astype
like that :-
metric_a = metric_a.astype('float')
metric_a[metric_a == j] = temp_a
print(metric_a[j])
output:-
1.0
CodePudding user response:
The reason was given by Jordan Hyatt in his comment. The problem is the declaration of the metric_X variables.
To build on his answer, be aware that just declaring it in an indivual line won't work. You have to make sure to use the np.zeros or at least use .copy().
What won't work as you are still referning the same memory space:
metric_a = np.zeros(10)
metric_b = metric_a
metric_c = metric_a
metric_d = metric_a
What will work as it creates a different object for each declared variable:
metric_a = np.zeros(10)
metric_b = metric_a.copy() # or np.zeros(10)
metric_c = metric_a.copy() # or np.zeros(10)
metric_d = metric_a.copy() # or np.zeros(10)