如何合并2个不同列的布尔数据帧?

时间:2018-01-21 16:38:25

标签: python pandas dataframe boolean

如何将df1和df2合并为df?

df1 = pd.DataFrame(list(zip(['4.txt', '5.txt', '6.txt'], [1,0,0], [1,1,1])),
             columns = ['file', 'is_about_heroes', 'is_about_pony'])


df2 = pd.DataFrame(list(zip(['5.txt', '6.txt'], [1,0], [1,0])),
         columns = ['file', 'is_about_pony', 'is_about_wolf'])
df1 

    file  is_about_heroes  is_about_pony
0  4.txt                1              1
1  5.txt                0              1
2  6.txt                0              1

df2    
    file  is_about_pony  is_about_wolf
0  5.txt              1              1
1  6.txt              0              0

我想得到df,这是前两个dfs的布尔联合。

df = pd.DataFrame(list(zip(['4.txt', '5.txt', '6.txt'], [1,0,0], [1,1,1], [0,1,0])),
                 columns = ['file', 'is_about_heroes', 'is_about_pony', 'is_about_wolf'])

    file  is_about_heroes  is_about_pony  is_about_wolf
0  4.txt                1              1              0
1  5.txt                0              1              1
2  6.txt                0              1              0

没有几个手动循环可以吗?

1 个答案:

答案 0 :(得分:2)

尝试使用merge

In [186]: df1.merge(df2, how='left').fillna(0)
Out[186]:
    file  is_about_heroes  is_about_pony  is_about_wolf
0  4.txt                1              1            0.0
1  5.txt                0              1            1.0
2  6.txt                0              1            0.0
相关问题