我在将这两个df以我想要的方式加入时遇到了一些麻烦。第一个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
最佳答案
我相信您已经设置了groupby结果和第二个数据帧的方式,此合并调用将起作用:
df = pd.merge(df1, df2, left_index=True, right_on=['STATE_PROV_CODE', 'COUNTY'])
它将解开MultiIndex;但是,如果您希望将其退回,那么您要做的就是
df = df.set_index(['STATE_PROV_CODE', 'COUNTY'])
关于python - Pandas 加入2列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25018952/