Home > Blockchain >  Change array's column value based on other array in Python
Change array's column value based on other array in Python

Time:12-22

I have two arrays. 2st array is subset of 1st array. as show below


    arr_1 = [[2,5,25],
             [2,6,28],
             [7,6,75],
             [8,4,39],
             [3,1,86],
             [1,4,45],
             [6,5,89],
             [3,4,99]]

    arr_2 = [[7,6,28],
             [8,4,65],
             [1,4,22],
             [6,5,33]]

arr_2's (column 1 (x coordinate) and column 2 (y coordinate)) have all values in arr_1's column1 and column 2) but column 3 (Temperature) of arr_2 has different values for the same x and y in arr_1. I have to replace the value of arr_1 Temperature column value with respect to coordinates (x and y) of arr_2. How can I do it?

Like this


    new_arr = [[2,5,25],
               [2,6,28],
               [7,6,28],    //75 of arr_1 changed to 28
               [8,4,65],    //39 of arr_1 changed to 65
               [3,1,86],
               [1,4,22],    //45 of arr_1 changed to 22 
               [6,5,33],    //89 of arr_1 changed to 33
               [3,4,99]]
    for i in range(len(self.dataset[key])):   
        ind = (np.array(self.pad["mesh_pos"][i])[:, None] == np.array(self.dataset["mesh_pos"][i])).all(-1).any(-1)
       
                
        id = np.array((ind==True).nonzero())[0]
        
        for k in range(len(id)):    
          ar[id[k],0] = self.dataset[key][i][0][k]  

        vr.append(ar)

      self.dataset[key] = np.stack(vr, axis=0)

I tried above method but my dataset is very huge and takes a lot of time to run. I am looking for numpy function that can make this faster. Can't share whole code Please help

CodePudding user response:

One possible way to solve your problem is to create a dictionary that maps the coordinates (x, y) to the temperature in arr_2, and then use this dictionary to update the temperature in arr_1.

Example:

# Create a dictionary that maps the coordinates (x, y) to the temperature in arr_2
temp_dict = {(x, y): temp for x, y, temp in arr_2}

# Initialize the new_arr variable with the same values as arr_1
new_arr = arr_1

# Iterate over the rows in arr_1
for i, (x, y, _) in enumerate(arr_1):
    # If the coordinates (x, y) are in the temp_dict, update the temperature value in new_arr
    if (x, y) in temp_dict:
        new_arr[i][2] = temp_dict[(x, y)]

print(new_arr)

Output:

[[2,5,25],
 [2,6,28],
 [7,6,28],   
 [8,4,65],   
 [3,1,86],
 [1,4,22],   
 [6,5,33],    
 [3,4,99]]

CodePudding user response:

You can compare each of the array with only the first 2 elements in each row and replace the rows which was matched:

arr_1[(arr_2[:,None,:2] == arr_1[:,:2]).all(-1).any(0)] = arr_2
  • Related