首页 > 解决方案 > 如何将函数的结果存储到具有相关列的数据框

问题描述

从函数返回数据作为字典并将其存储在数据框中。使用 for 循环运行它时出现错误。

import pyowm
from pyowm.utils import config
from pyowm.utils import timestamps
owm = pyowm.OWM(" your free api key from OpenWeatherMap")
mgr = owm.weather_manager()

data =[]
# Create function to get weather details
def get_weather(city):
    observation = mgr.weather_at_place(city)
    l = observation.weather
    Wind_Speed = l.wind()['speed']
    Temp = l.temperature('celsius')['temp']
    Max_temp = l.temperature('celsius')['temp_max']
    Min_temp = l.temperature('celsius')['temp_min']
    #Heat_index = l.heat_index
    Humidity = l.humidity
    Pressure = l.pressure['press']
    weather = {"City": city, "Wind_Speed" : Wind_Speed, "Temp": 
                    Temp,"Max_temp":Max_temp, "Min_temp":Min_temp, 
                    "Humidity":Humidity, "Pressure":Pressure}
    return weather


for city in df_location['City']:
    get_weather(city)
    df = df.append(data, True)  

想要将天气详细信息存储在与相关城市相同的 df 中。

当前的 df_location 是这样的: 在此处输入图像描述

标签: pythonpandasdataframedictionary

解决方案


推荐阅读