Search⌘ K
AI Features

Solution: DataFrame Operations

Explore how to perform DataFrame operations using GeoPandas by merging city and country datasets, filtering for African cities, setting geometry columns, and exporting data to CSV and PNG formats for analysis and visualization.

We'll cover the following...

Let's take a look at the solution and review the code:

Python 3.10.4
import geopandas as gpd
import pandas as pd
# Load cities and countries
cities = gpd.read_file('populated_places.geojson')
countries = gpd.read_file('countries.geojson')
# Join both DataFrames
merged = pd.merge(countries, cities, left_on='sovereignt', right_on='sov0name', how='inner')
# filter by population size
filtered = merged.query("continent == 'Africa'")
# When we merge, we need to reset the geometry
filtered = filtered.set_geometry('geometry_y')
# save the CSV
filtered.to_csv('output/african_cities.csv')
# Save the PNG
ax = filtered.plot(figsize=(7, 7))
ax.set_ylabel('Latitude')
ax.set_xlabel('Longitude')
ax.figure.savefig('output/african_cities.png', dpi=300)

  • Lines 1–2: As always, we import the necessary libraries.

  • Lines 5–6: We open the cities and the countries ...