熊猫数据框合并

时间:2017-05-24 14:23:09

标签: python pandas dataframe merge

我是熊猫新手。我正在尝试使用邮政编码,邮政编码中的人口和邮政编码中的县数制作数据集。

我从人口普查网站获取数据: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'>

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']]

1 个答案:

答案 0 :(得分:1)

我认为您需要添加reset_index,因为value_counts的输出为Series,需要DataFrame的列为2列:

zcta_ct_county = df['ZCTA5'].value_counts().reset_index()