【问题标题】:How to create function to pass lat long in api call for get weather data如何创建函数以在 api 调用中传递 lat long 以获取天气数据
【发布时间】:2021-04-29 10:51:32
【问题描述】:

我尝试使用城市名称从 pyOWM 包中获取数据,但在某些情况下由于城市拼写错误 没有获取数据,它会破坏流程。

我想使用 lat-long 获取天气数据,但不知道如何为其设置功能。

Df1:
-----
User      City              State               Zip      Lat         Long
-----------------------------------------------------------------------------
 A    Kuala Lumpur    Wilayah Persekutuan      50100    5.3288907   103.1344397        
 B    Dublin          County Dublin             NA      50.2030506  14.5509842
 C    Oconomowoc      NA                        NA      53.3640384  -6.1953066
 D    Mumbai          Maharashtra              400067   19.2177166  72.9708833
 E    Mratin          Stredocesky kraj         250 63   40.7560585  -5.6924778
.
.
.
----------------------------------
Code:
--------
import time
from tqdm.notebook import tqdm
import pyowm
from pyowm.utils import config
from pyowm.utils import timestamps


cities = Df1["City"].unique().tolist()
cities1 = cities [:5]

owm = pyowm.OWM('bee8db7d50a4b777bfbb9f47d9beb7d0')
mgr = owm.weather_manager()

'''
Step-1 Define list where save the data
'''
list_wind_Speed =[]
list_tempreture =[]
list_max_temp =[]
list_min_temp =[]
list_humidity =[]
list_pressure =[]
list_city = []
list_cloud=[]
list_status =[]
list_rain =[]
'''
Step-2 Fetch data
'''
j=0
for city in tqdm(cities1):
    j=+1
    if j < 60:  

#           one_call_obs = owm.weather_at_coords(52.5244, 13.4105).weather
#           one_call_obs.current.humidity

            observation = mgr.weather_at_place(city)

            l = observation.weather
            list_city.append(city)
            list_wind_Speed.append(l.wind()['speed'])
            list_tempreture.append(l.temperature('celsius')['temp'])
            list_max_temp.append(l.temperature('celsius')['temp_max'])
            list_min_temp.append(l.temperature('celsius')['temp_min'])
            list_humidity.append(l.humidity)
            list_pressure.append(l.pressure['press'])
            list_cloud.append(l.clouds)
            list_rain.append(l.rain)
   else:
        time.sleep(60)
        j=0

'''
Step-3 Blank data frame and store data in that
'''
df2 = pd.DataFrame()
df2["City"] = list_city
df2["Temp"] = list_tempreture
df2["Max_Temp"] = list_max_temp
df2["Min_Temp"] = list_min_temp
df2["Cloud"] = list_cloud
df2["Humidity"] = list_humidity
df2["Pressure"] = list_pressure
df2["Status"] = list_status
df2["Rain"] = list_status
df2

从上面的代码,我得到如下结果,

City        | Temp |Max_Temp|Min_Temp|Cloud |Humidity|Pressure |Status         | Rain
------------------------------------------------------------------------------------------
Kuala Lumpur|29.22 |30.00   |27.78   | 20   |70      |1007     | moderate rain | moderate rain
Dublin      |23.12 |26.43   |22.34   | 15   |89      | 978     | cloudy        | cloudy
...

现在由于一些城市错字错误进程停止, 寻找它的替代解决方案并尝试从 Lat-Long 获取天气数据,但不知道如何设置传递 lat & long 列数据的函数。

Df1 = {'User':['A','B','C','D','E'],
        'City':['Kuala Lumpur','Dublin','Oconomowoc','Mumbai','Mratin'], 
        'State':['Wilayah Persekutuan','County Dublin',NA,1'Maharashtra','Stredocesky kraj'],
           'Zip': [50100,NA,NA,400067,250 63],  
           'Lat':[5.3288907,50.2030506,53.3640384,19.2177166,40.7560585],
            'Long':[103.1344397,14.5509842,-6.1953066,72.9708833,-5.6924778]}

# Try to use this code to get wather data
#           one_call_obs = owm.weather_at_coords(52.5244, 13.4105).weather
#           one_call_obs.current.humidity
Expected Result
--------------
User | City | Lat | Long | Temp | Cloud | Humidity | Pressure | Rain | Status
-----------------------------------------------------------------------------

【问题讨论】:

  • 要查看它的不同功能,我检查了它的Doc

标签: python pandas dataframe openweathermap


【解决方案1】:

如果找不到城市,则捕获错误,从数据框中解析纬度/经度。使用该纬度/经度创建一个边界框,并使用weather_at_places_in_bbox 获取该区域的观察列表。

import time
from tqdm.notebook import tqdm
import pyowm
from pyowm.utils import config
from pyowm.utils import timestamps
import  pandas as pd
from pyowm.commons.exceptions import NotFoundError, ParseAPIResponseError

df1 = pd.DataFrame({'City': ('Kuala Lumpur', 'Dublin', 'Oconomowoc', 'Mumbai', 'C airo', 'Mratin'),
 'Lat': ('5.3288907', '50.2030506', '53.3640384', '19.2177166', '30.22', '40.7560585'),
 'Long': ('103.1344397', '14.5509842', '-6.1953066', '72.9708833', '31',  '-5.6924778')})


cities = df1["City"].unique().tolist()

owm = pyowm.OWM('bee8db7d50a4b777bfbb9f47d9beb7d0')
mgr = owm.weather_manager()

for city in cities:
  try:
    observation = mgr.weather_at_place(city)
    # print(city, observation)
  except NotFoundError:
    # get city by lat/lon
    lat_top = float(df1.loc[df1['City'] == city, 'Lat'])
    lon_left = float(df1.loc[df1['City'] == city, 'Long'])
    lat_bottom = lat_top - 0.3
    lon_right = lon_left + 0.3
    try: 
      observations = mgr.weather_at_places_in_bbox(lon_left, lat_bottom, lon_right, lat_top, zoom=5)  
      observation = observations[0]
    except ParseAPIResponseError:
      raise RuntimeError(f"Couldn't find {city} at lat: {lat_top} / lon: {lon_right}, try tweaking the bounding box")

  weather = observation.weather
  temp = weather.temperature('celsius')['temp']
  print(f"The current temperature in {city} is {temp}")

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 1970-01-01
    • 2019-05-28
    • 2017-03-17
    • 2022-12-18
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2020-07-24
    相关资源
    最近更新 更多