Home > Software design >  Looping through values obtained from Dataframe and creating a new variable
Looping through values obtained from Dataframe and creating a new variable

Time:01-08

I have a Dataframe that has latitude and longitude of a bunch of address as below

lat, long
25.234, -76.433
25.175, -74.843

Raw input:

df = pd.DataFrame({'lat': [25.234, 25.175], 'long': [-76.433, -74.843]})

I am trying to create a variable that stores values pulled from this Dataframe and creates value as below.

value = '(SQRT(POW(69.1 * (S.latitude - latitude_value), 2)   POW(69.1 * (longitude_value - S.longitude) * COS(S.latitude / 57.3), 2)) <= 0.2)'

How can I loop through each row and have this value variable have all the lat/ long created in the above format

Expected output:

value = '(SQRT(POW(69.1 * (S.latitude - 25.234), 2)   POW(69.1 * (-76.433 - S.longitude) * COS(S.latitude / 57.3), 2)) <= 0.2) OR 
         (SQRT(POW(69.1 * (S.latitude - 25.175), 2)   POW(69.1 * (-74.843 - S.longitude) * COS(S.latitude / 57.3), 2)) <= 0.2)'

CodePudding user response:

You can replace 'latitude_value' and 'longitude_value' in value with {} so that you can use str.format method in apply function to fill in the string's placeholder.

value = '(SQRT(POW(69.1 * (S.latitude - latitude_value), 2)   POW(69.1 * (longitude_value - S.longitude) * COS(S.latitude / 57.3), 2)) <= 0.2)'.replace('latitude_value', '{}').replace('longitude_value', '{}')

out = ' OR '.join(df.apply(lambda x: value.format(x['lat'], x['long']), axis=1).tolist())

Output:

'(SQRT(POW(69.1 * (S.latitude - 25.234), 2)   POW(69.1 * (-76.433 - S.longitude) * COS(S.latitude / 57.3), 2)) <= 0.2) OR (SQRT(POW(69.1 * (S.latitude - 25.175), 2)   POW(69.1 * (-74.843 - S.longitude) * COS(S.latitude / 57.3), 2)) <= 0.2)'
  •  Tags:  
  • Related