遍历API响应时Pandas DataFrame仅单个列数据异常
问题修复:遍历天气API时DataFrame「Desc」列值全部重复的问题
问题现象
遍历多个邮编调用OpenWeatherMap API获取天气数据时,生成的Pandas DataFrame中「Desc」列所有值均与最后一个邮编的天气描述相同(示例中全为Clouds),但单独运行邮编32303时,能得到正确的Clear结果,说明遍历逻辑存在错误。
错误原因
循环内的description = response['weather'][0]['main']是直接对变量赋值,而非像其他数据列那样使用append()将结果添加到列表中。每次循环都会覆盖description变量的内容,最终生成DataFrame时,该变量仅保留最后一次循环的结果,导致整列值重复。
修复后的完整代码
import requests import pandas as pd api_key = 'a14ac278e4c4fdfd277a5b37e1dbe87a' # Create a dictionary of zip codes for the team zip_codes = { 55446: "You", 16823: "My Boo", 94086: "Your Boo", 32303: "Mr. Manatee", 95073: "Me" } # Create a list of zip codes zip_list = list(zip_codes.keys()) # Create a list of names name_list = list(zip_codes.values()) # For team data, create a pandas DataFrame from the dictionary df1 = pd.DataFrame(list(zip_codes.items()), columns=['Zip Code', 'Name']) # Create empty lists to hold the API response data city_name = [] description = [] weather = [] feels_like = [] wind = [] clouds = [] # Loop through each zip code for zip_code in zip_list: # Make a request to the OpenWeatherMap API url = f"http://api.openweathermap.org/data/2.5/weather?zip={zip_code},us&units=imperial&appid={api_key}" response = requests.get(url).json() # Store the response data in the appropriate empty list city_name.append(response['name']) # 修复:将赋值改为列表追加操作 description.append(response['weather'][0]['main']) weather.append(response['main']['temp']) feels_like.append(response['main']['feels_like']) wind.append(response['wind']['speed']) clouds.append(response['clouds']['all']) # rain.append(response['humidity']['value']) # For weather data, create df from lists df2 = pd.DataFrame({ 'City': city_name, 'Desc': description, 'Temp (F)': weather, 'Feels like': feels_like, 'Wind (mph)': wind, 'Clouds %': clouds, # 'Rain (1hr)': rain, }) # Merge df1 & df2, round decimals, and don't display index or zip. df3=pd.concat([df1,df2],axis=1,join='inner').drop('Zip Code', axis=1) df3[['Temp (F)', 'Feels like', 'Wind (mph)', 'Clouds %']] = df3[['Temp (F)', 'Feels like', 'Wind (mph)', 'Clouds %']].astype(int) # Don't truncate df pd.set_option('display.width', 150) # Print the combined DataFrames display(df3.style.hide_index())
关键修复点
将循环内的description = response['weather'][0]['main']修改为description.append(response['weather'][0]['main']),确保每次循环都把当前邮编对应的天气描述添加到description列表中,与其他数据列表的存储逻辑保持一致,生成DataFrame时就能对应每个邮编的正确天气描述。
内容的提问来源于stack exchange,提问作者Cath Tyner
相关产品推荐
相关产品推荐

