PineNuts0
PineNuts0

Reputation: 5234

Python: How to pass or loop lat / long coordinates from a data frame into a function

I have a long function which I will not include in here. The final line of the function is as follows:

get_hourly_WSI_latlong_historical (datetime.date(2015,1,1), datetime.date(2015,2,1), 39.78681, -104.937, fields = None)

The above function and line of code run successfully. However, I want to create a data frame with multiple lat/long coordinates that can be passed through the code above. Sample data frame file:

lat        long         
42.281     83.743              
42.1784    87.9979              
40.7128    74.0059      

I want to run the function for each lat / long in my list dynamically using a loop. So those coordinates in my data frame above will replace the 39.78681, -104.937 I currently have in my code.

Any help on this would be greatly appreciated.

Upvotes: 1

Views: 359

Answers (1)

jezrael
jezrael

Reputation: 863116

I think you can use apply:

df1 = df.apply(lambda x: get_hourly_WSI_latlong_historical (datetime.date(2015,1,1), 
                                                            datetime.date(2015,2,1), 
                                                            x.lat, x.long, fields = None),
                                                            axis=1)

Sample:

df = pd.DataFrame({'lat':[42.281,42.1784,40.7128],
                   'long':[83.743,87.9979,74.0059]})

print (df)
       lat     long
0  42.2810  83.7430
1  42.1784  87.9979
2  40.7128  74.0059

def get_hourly_WSI_latlong_historical(date1,date2, lat,long, fields):
    return pd.Series([lat + 10, long - 10], index=['lat1','long1'])

df1 = df.apply(lambda x: get_hourly_WSI_latlong_historical (datetime.date(2015,1,1), 
                                                            datetime.date(2015,2,1), 
                                                            x.lat, x.long, fields = None),
                                                            axis=1)

print (df1)                                                            
      lat1    long1
0  52.2810  73.7430
1  52.1784  77.9979
2  50.7128  64.0059

Upvotes: 1

Related Questions