How to pass a file as argument to parameter in Python in a specific format?

Viewed 96

I have a file or dataframe like below containing city name , latitude and longitude.

city.head(4)
    City    Latitude    Longitude
    Seattle 47.620422   122.349358
    Dubai   25.276987   55.296249
    Mexico  19.432608   99.1332
    Tokyo   35.652832   139.839478

I want pass all the lattitude and longitude from city dataframe to an API and get the corresponding results. Currently I able to pass providing feeding lat and long as input to the parms.

How can I automate the entire steps. Lat and Long should be passed into params in this format lat:long****( first 3 decimals points should be extracted from the city dataframe)

import requests

headers = {
    'Authorization': 'Api-Key ',
}

params = (
    ('coords', '49.910:10.920, 47.620:122:349'),
)

response = requests.get('https://api.example.com/we/v12/forecasts', headers=headers, params=params)

Sample Output of API

'{"results":[{"place":{"type":"locode","value":"PLWRO"},"measures":[{"ts":1572177600000,"t2m":19.6,"t_min":12.16,"t_max":20.59,"wspd":26,"dir":"W","wgust":37,"rh2m":44,"prsmsl":1015,"skcover":"clear","precip":0.0,"snowd":0,"thunderstorm":"N","fog":"L"}]},{"place":{"type":"locode","value":"DEHAM"},"measures":[{"ts":1572177600000,"t2m":10.49,"t_min":8.18,"t_max":10.6,"wspd":21,"dir":"W","wgust":39,"rh2m":69,"prsmsl":1016,"skcover":"partly_cloudy","precip":0.0,"snowd":0,"thunderstorm":"N","fog":"L"}]}]}'

How can this be done.

2 Answers

Round the float columns to 3rd decimal and then convert to string. Combine the columns needed. Iterate the column and send data to the API.

>>> df = df.round(3).astype(str)
>>> df
      City Latitude Longitude
0  Seattle    47.62   122.349
1    Dubai   25.277    55.296
2   Mexico   19.433    99.133
3    Tokyo   35.653   139.839
>>> df['LatLong'] = df.Latitude.add(':') + df.Longitude
>>> df
      City Latitude Longitude         LatLong
0  Seattle    47.62   122.349   47.62:122.349
1    Dubai   25.277    55.296   25.277:55.296
2   Mexico   19.433    99.133   19.433:99.133
3    Tokyo   35.653   139.839  35.653:139.839

>>> df.LatLong.str.cat(sep=', ')
'47.62:122.349, 25.277:55.296, 19.433:99.133, 35.653:139.839'

One Liner

>>> df.Longitude.str.cat(df.Latitude, sep=':').str.cat(sep=', ')

I agree with Vishnudev's answer, but that particular way of doing so would require you to transform your original data, which may not be the best way to deal with the situation.

In order to conserve the original data, you can create a small set of calculated columns in your dataframe like this:

df['latp'] = round(df['Latitude'], 3)
df['lonp'] = round(df['Longitude'], 3)

df['param'] = df['latp'].astype(str) + ':' + df['lonp'].astype(str)

...and pass the 'param' column as a parameter.

Cheers!

Related