熊猫加入2列

时间:2014-07-29 15:19:02

标签: python join pandas

我在让这两个dfs加入我想要的方式时遇到了一些麻烦。第一个df具有我使用df1 = df3.groupby(["STATE_PROV_CODE", "COUNTY"]).size()创建的分层索引,以获取每个县的计数。

STATE_PROV_CODE  COUNTY            COUNT
AL               Autauga County      1
                 Baldwin County      1
                 Barbour County      1
                 Bibb County         1
                 Blount County       1

    STATE_PROV_CODE COUNTY  ANSI Cl FIPS
0   AL  Autauga County  H1  01001
1   AL  Baldwin County  H1  01003
2   AL  Barbour County  H1  01005
3   AL  Bibb County     H1  01007
4   AL  Blount County   H1  01009

在SQL中,我想执行以下操作:

SELECT STATE_PROV_CODE, COUNTY, FIPS, COUNT,
FROM df1, df2
ON STATE_PROV_CODE, COUNTY
WHERE df1.STATE_PROV_CODE = df2.STATE_PROV_CODE
AND df1.COUNTY = df2.COUNTY

我希望结果如下:

STATE_PROV_CODE  COUNTY            COUNT    FIPS
AL               Autauga County      1     01001
                 Baldwin County      1     01003
                 Barbour County      1     01005
                 Bibb County         1     01007
                 Blount County       1     01009

1 个答案:

答案 0 :(得分:2)

我相信你设置groupby结果和第二个数据帧的方式,这个合并调用将起作用:

df = pd.merge(df1, df2, left_index=True, right_on=['STATE_PROV_CODE', 'COUNTY'])

它会解开MultiIndex;但是,如果你想要它,你所要做的就是

df = df.set_index(['STATE_PROV_CODE', 'COUNTY'])