Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through values obtained from Dataframe and creating a new variable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)'

>Solution :

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)'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading