简体   繁体   中英

Empty GeoDataFrame when using .merge GeoPandas

I'm trying to merge a pandas dataframe and a geopandas geodataframe by using an attribute joins. I'm using a US counties shape file ( https://geonet.esri.com/thread/24614 first response) and a csv file ( http://water.usgs.gov/watuse/data/2010/index.html the first Excel format then saved as a csv). Once the dataframes are joined by using FIPS I try to print the new geodataframe, but only the headers print with the message Empty GeoDataFrame above. Here's the code I'm using

from matplotlib import pyplot as plt
import csv 
import numpy as np
import datetime
import pandas as pd
import geopandas as gpd
import csv
from shapefile import Reader 

df1 = pd.read_csv('usco2010.csv') 
#Reads csv file and puts it into a dataframe
df2 = pd.DataFrame({'STATE':df1['STATE'],'COUNTY':df1['COUNTY'],'FIPS':df1['FIPS'],'Se    rPop10^3':df1['TP-TotPop'],'WtrWthdrwl_MGD':df1['PS-WSWFr']})  
#Takes the data we want from df1 and creates a new dataframe df2: Statename, County name, FIPS, Served Population in 1000s, Surface water withdrawls in MGD 


counties = gpd.read_file('UScounties') 
#creates a GeoDataFrame for the US counties by using UScounties shapefile

print(counties.head())
print(df2.head())

counties = counties.merge(df2, on='FIPS') #Empty GeoDataFrame
#merges counties and df2 with same FIPS

print(counties)

Shouldn't the GeoDataFrame have the data from both objects being merged? I'd like to make a Choropleth Maps for fresh surface water withdraws.

Sorry if we're not suppose to list the data we use, I wanted to be as specific as possible. I'm new to python so I apologize if this is a simple question, but google and a search on this site do not show similar questions that have been answered

Just checked your problem. From what I see, the problem was that the columns you were trying to merge on where of two different data types. Your column in the counties dataset was of a type object (eg it contained strings) while the df2["FIPS"] was of type "int64". This is what I did, and the merge work. Still give it a check to see if the merged was appropriately carried out:

us_data = pd.read_csv('usco2010.csv') 
counties = gp.read_file('UScounties.shp') 
counties["FIPS"] = counties["FIPS"].astype(int)
pd.merge(counties, us_data, on="FIPS")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM