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 gpdimport pandas as pd# Load cities and countriescities = gpd.read_file('populated_places.geojson')countries = gpd.read_file('countries.geojson')# Join both DataFramesmerged = pd.merge(countries, cities, left_on='sovereignt', right_on='sov0name', how='inner')# filter by population sizefiltered = merged.query("continent == 'Africa'")# When we merge, we need to reset the geometryfiltered = filtered.set_geometry('geometry_y')# save the CSVfiltered.to_csv('output/african_cities.csv')# Save the PNGax = 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 ...