python - 合并数据帧以包含指示行属于哪些数据帧的列

标签 python pandas dataframe

我有两个 Dataframe(a 是可哈希的,b 是不可哈希的)

   Foo              
    a   b           
A   1   2       
B   1   3       
C   0   4       

 Bar
a   b
A   1   2
D   0   6

如果索引或代码(本例中为 A、B、C、D)相同,则 a 和 b 必须相同。 我想知道如何合并这两个数据框,显示列所属的位置,如下所示。

    a   b   Foo   Bar
A   1   2    1     1
B   1   3    1     0
C   0   4    1     0
D   0   6    0     1

获取此数据帧的最有效方法是什么?

最佳答案

您应该能够使用df.merge来做到这一点:

df1['Foo'] = 1
df2['Bar'] = 1
out = df1.merge(df2, on=['a', 'b'], how='outer').fillna(0).astype(int)

print(out)
   a  b  Foo  Bar
0  1  2    1    1
1  1  3    1    0
2  0  4    1    0
3  0  6    0    1

关于python - 合并数据帧以包含指示行属于哪些数据帧的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45974463/

相关文章:

python - 将字典列表转换为 DataFrame 时出现类型错误

python - 我在理解如何正确使用 pandas 旋转数据框时遇到问题

Python删除请求rest api(on gae)

python - 使用 Selenium (Python3) 抓取网站的多个页面

python - 从 Twisted 中的服务访问 ServerFactory

Python re 模块 -\b 和 '-' 出现意外行为

python - 如何在 Pandas 数据框列中查找关键字并通过虚拟变量分配标签?

python - 在 IPython Notebook 中显示所有 pandas 数据帧

python - 将 pandas 中的字典拆分为单独的列

dataframe - Julia reshape 多维数组的最佳方法