Search code examples
arrayspython-3.xdata-analysis

How to subtract every value of one array from another array to find location of where value of array 1 minus value of array 2 = 0?


I want to find pairs between given latitude and longitude values to output a temperature value. For example, let's say this is the data I have available:

lat1=[0,1,2,3,4,5,6,7,8]
lon2=[0,1,2,3,4,5,6,7,7]
temp=[2,3,4,5,6,7,8,9,10]

and here is the latitude and longitude values I have to obtain a temp value for:

lat2=[0,1,2,3,8]

lon2=[0,1,2,3,7]

With this example, I would want my code to output temperature values for each latitude and longitude pair. So it would output the following temperature for the given latitude and longitude values:

temp=[2,3,4,10]

Below is my attempt. My idea was to find anywhere where the data latitude and longitude values subtracted from the needed latitude and longitude values would equal 0, meaning they're the same. I would then get the position where this occurs, and further print this same position with the temperature data. However, this code outputs the following error:

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Any help with my current code or further suggestions would be greatly appreciated! Thank you so much.

'''
import numpy as np 

def findpairs(lat1,lat2,lon1,lon2,a,b,c,d):
    for i in range (0,a):
        for j in range (0,b):
            for k in range (0,c):
                for l in range (0,d):
                    if ((lat1[0:]-lat2[0:]==0) and (lon1[0:]-lon2[0:]==0)):
                        print (np.where(lat2[j]))



#driver code 
lat1 = [1, 2, 7, 5, 3] 
lon1 = [ 7, 4, 3, 2, 1,0] 
lat2=[1,2,3,7,5,3]
lon2=[7,4,3,2,1,9,0]
a=len(lat1)
b=len(lon1)
c=len(lat2)
d=len(lon2)
findpairs(lat1,lat2,lon1,lon2,a,b,c,d)

'''


Solution

  • You can create a dict that maps coordinates to temperatures, so that you can use it to map the requested coordinates to the respective temperatures:

    def get_temp(lat1, lat2, lon1, lon2, temp):
        return list(map(dict(zip(zip(lat1, lon1), temp)).get, zip(lat2, lon2)))
    

    so that given:

    lat1 = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    lon1 = [0, 1, 2, 3, 4, 5, 6, 7, 7]
    temp = [2, 3, 4, 5, 6, 7, 8, 9, 10]
    lat2 = [0, 1, 2, 3, 8]
    lon2 = [0, 1, 2, 3, 7]
    

    get_temp(lat1, lat2, lon1, lon2, temp) would return:

    [2, 3, 4, 5, 10]
    

    Note that your expected output is missing a 5 since that's what (3, 3) should map to.