You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列表转换为DataFrame问题:无法将全部元素存入列表及DataFrame

Fixing Your Geocoding List & DataFrame Issue

Hey there! I see exactly what's going wrong here—let's break it down and fix it step by step.

The Core Problem

In your loop, you're reassigning the quartier_coord list every time instead of adding to it:

quartier_coord = [{'Neighbourhood': quartier, 'Latitude': latitude, 'Longitude': longitude}]

This line replaces the entire list with a new one that only contains the current neighborhood's data. By the end of the loop, only the last entry is left because all previous ones got overwritten.

Fixed Code

Here's the corrected version, plus a couple of key optimizations:

from geopy.geocoders import Nominatim
import pandas as pd

quartiers = ['Centre-ville','Bellevue - Chantenay - Sainte-Anne','Dervallières - Zola','Hauts-Pavés - Saint-Félix','Malakoff - Saint-Donatien','Île de Nantes','Breil - Barberie', 'Nantes Nord', 'Nantes Erdre', 'Doulon - Bottiere', 'Nantes Sud']
quartier_coord = []

# Initialize the geolocator ONCE outside the loop (better for performance/API limits)
geolocator = Nominatim(user_agent="nantes_explorer_2")

for quartier in quartiers:
    address = '{}, Nantes, France'.format(quartier)
    try:
        location = geolocator.geocode(address)
        if location:
            latitude = location.latitude
            longitude = location.longitude
            print('The geograpical coordinates of {} are {}, {}.'.format(quartier, latitude, longitude))
            # Use .append() to add the new dictionary to the list
            quartier_coord.append({'Neighbourhood': quartier, 'Latitude': latitude, 'Longitude': longitude})
        else:
            print(f"Could not find coordinates for {quartier}")
    except Exception as e:
        print(f"Error geocoding {quartier}: {str(e)}")

# Convert to DataFrame
df = pd.DataFrame(quartier_coord)
print(df)

Key Changes Explained

  1. Use .append() instead of reassigning: This adds each new neighborhood's data to the end of the existing list, preserving all entries.
  2. Move geolocator outside the loop: Creating a new Nominatim instance every iteration is unnecessary and could trigger rate limits from the API. Initializing once is more efficient.
  3. Add error handling: Wrapping the geocoding logic in a try-except block prevents your script from crashing if a neighborhood can't be geocoded (e.g., typos, API downtime).

Why Your Print Statements Worked

Your print calls inside the loop were working because they ran for every neighborhood before the list got overwritten. The issue only showed up when you checked the final list, since it had been replaced 10 times.

After making these changes, your quartier_coord list will contain all 11 neighborhoods, and converting it to a DataFrame will give you the full dataset you need.

内容的提问来源于stack exchange,提问作者carolche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:44:06