1
我是熊貓新手。我正在嘗試製作一個帶有郵政編碼,該郵政編碼中的人口數字和郵政編碼中的縣數的數據集。熊貓數據框合併
我從人口普查網站上的數據:https://www2.census.gov/geo/docs/maps-data/data/rel/zcta_county_rel_10.txt
我用下面的代碼很努力,但它不工作。你能幫我弄清楚正確的代碼嗎?我有一個預感,錯誤是由於數據框或與數據類型相關的排序。但是我無法弄清楚正確的代碼是否正確。請讓我知道你的想法。先謝謝你!
import pandas as pd
df = pd.read_csv("zcta_county_rel_10.txt", dtype={'ZCTA5': str, 'STATE': str, 'COUNTY': str}, usecols=['ZCTA5', 'STATE', 'COUNTY', 'ZPOP'])
zcta_pop = df.drop_duplicates(subset={'ZCTA5', 'ZPOP'}).drop(['STATE', 'COUNTY'], 1)
zcta_ct_county = df['ZCTA5'].value_counts()
zcta_ct_county.columns = ['ZCTA5', 'CT_COUNTY']
pre_merge_1 = pd.merge(zcta_pop, zcta_ct_county, on='ZCTA5')[['ZCTA5', 'ZPOP', 'CT_COUNTY']]
這是我的錯誤信息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python27/lib/python2.7/site-packages/pandas/tools/merge.py", line 58, in merge copy=copy, indicator=indicator)
File "/usr/local/python27/lib/python2.7/site-packages/pandas/tools/merge.py", line 473, in __init__ 'type {0}'.format(type(right)))
ValueError: can not merge DataFrame with instance of type <class 'pandas.core.series.Series'>
SOLUTION
import pandas as pd
df = pd.read_csv("zcta_county_rel_10.txt", dtype={'ZCTA5': str, 'STATE': str, 'COUNTY': str}, usecols=['ZCTA5', 'STATE', 'COUNTY', 'ZPOP'])
zcta_pop = df.drop_duplicates(subset={'ZCTA5', 'ZPOP'}).drop(['STATE', 'COUNTY'], 1)
zcta_ct_county = df['ZCTA5'].value_counts().reset_index()
zcta_ct_county.columns = ['ZCTA5', 'CT_COUNTY']
pre_merge_1 = pd.merge(zcta_pop, zcta_ct_county, on='ZCTA5')[['ZCTA5', 'ZPOP', 'CT_COUNTY']]
如果您回答了您自己的問題,您應該將解決方案作爲答案發布,並將其標記爲「已接受」(而不是將其留在問題本身中)。 –
感謝提醒,@jezrael幫我解決了這個問題。該解決方案發布在我的帖子底部。下面接受jezrael的答案。 – Counter10000