python - Pandas 加入 2 列

标签 python join pandas

我在让这两个 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/

相关文章:

sql - 如何缩短我对 StackExchange 的 SQL 查询?

python - pandas 按列表查询行

python - 在 Pandas 中使用 read_csv 读取最后几行

python - 使用 python : execute service or systemd or init. d 脚本进行进程管理

java - Hibernate 使用条件连接

r - 使用 data.table 包通过引用进行条件二进制连接和更新

python - 有条件地设置 Pandas 中组的值python

python Pandas : How to sum up columns that also include missing values?

python - 如何摆脱打印语句中多余的 + 符号,Python

python - Python 3 : How/when to call it? 中的 PyEval_InitThreads(传奇继续令人作呕)