列表转换为DataFrame问题:无法将全部元素存入列表及DataFrame
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
- Use
.append()instead of reassigning: This adds each new neighborhood's data to the end of the existing list, preserving all entries. - Move
geolocatoroutside the loop: Creating a new Nominatim instance every iteration is unnecessary and could trigger rate limits from the API. Initializing once is more efficient. - Add error handling: Wrapping the geocoding logic in a
try-exceptblock 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

