【问题标题】:how to merge 2 boolean dataframes with different columns?如何合并 2 个具有不同列的布尔数据框?
【发布时间】:2018-01-21 16:38:24
【问题描述】:

如何将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,它是前两个 df 的布尔联合。

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

是否可以不用多次手动循环?

【问题讨论】:

  • 对于is_about_pony 中的文件6.txt,您在df1df2 之间存在冲突
  • @James 这不是冲突。有布尔意义。考虑一些算法给我df1,另一个给我df2。我想对 df1 和 df2 使用逻辑或。对于 6.txt,那么我有 True OR False,在结果 df 中它应该是 True。问题是:如果值是布尔值,如何使用数据框进行操作。如何进行逻辑运算?在我的特殊情况下,数据框具有不同的形状。如何以这种特殊方式处理。

标签: python pandas dataframe boolean


【解决方案1】:

尝试使用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

【讨论】:

  • 如何防止类型改变?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 2018-03-21
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
相关资源
最近更新 更多