【问题标题】:Why isn't this looping over my whole file of zip codes?为什么这不会遍历我的整个邮政编码文件?
【发布时间】:2019-06-10 18:33:18
【问题描述】:

当我运行我的代码并在我的 for 循环中添加打印语句时,邮政编码、城市和地区会正确打印出第一个邮政编码,但它永远不会进入我的下一个邮政编码。当我打印出我的 DataFrame 时,所有值都设置为 NaN。

我尝试运行一个通用的 for 循环来在 PyCharm 中分别打印每个邮政编码,它只打印第一个邮政编码,但是当我在 Jupyter Notebook 中运行相同的代码时,每个邮政编码都会打印出来

for z in zipcodes:

    # gets the website to find the closest big city
    res = requests.get('https://www.travelmath.com/cities-near/' + z)
    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    elems = soup.select('#EchoTopic > div:nth-child(1) > ul:nth-child(8) > li:nth-child(1) > a:nth-child(2)')
    place = elems[0].text.strip()
    city, state = place.split(',')

    # uses the city found above to find the text in the webpage and the region it corresponds to
    newres = requests.get('https://www.almanac.com/weather/longrange')
    newsoup = bs4.BeautifulSoup(newres.text, 'html.parser')
    newelems = newsoup.find('td', text=city).parent.parent
    alltext = newelems.text
    region = find_region(alltext) # helper regex function I wrote

    # appends the zip code, city, and region to the DataFrame
    regions.append([z, city, region])

只打印出第一个邮政编码、城市和地区,并返回一个 NaN 的 DataFrame,而不是打印出近 4,000 个邮政编码及其相关信息,并且不将任何信息写入 DataFrame

【问题讨论】:

    标签: python-3.x pandas dataframe beautifulsoup


    【解决方案1】:

    当你使用追加数据框方法时,你需要做一个赋值。

    尝试添加:

    regions = regions.append([z,city,region])
    

    【讨论】:

    • 这有助于更新 DataFrame,但我仍然无法让它循环到下一个邮政编码。我检查了列表的长度并添加了打印语句以查看它是否再次启动循环并且它永远不会。
    【解决方案2】:

    代码试图遍历我的 DataFrame 的列,这恰好是第一个邮政编码,因为我的 csv 中没有列标题。随着 Dan Wisner 的回答,我改变了:

    for i in zipcodes.index:
        z = zipcodes.iloc[i]['zip codes']
        res = requests.get('https://www.travelmath.com/cities-near/' + str(z))
        ...
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多