...

/

Solution: DataFrame Operations

Solution: DataFrame Operations

A solution to the DataFrame Operations exercise.

We'll cover the following...

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

Press + to interact
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 ...