Python 如何合并具有不同列的2个布尔数据帧?
如何将df1和df2合并到df中Python 如何合并具有不同列的2个布尔数据帧?,python,pandas,dataframe,boolean,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 = ['
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'])
我想得到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
没有几个手动循环是否可能?尝试使用
合并:
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
对于is-about\u-pony
@James中的文件6.txt
,在df1
和df2
之间存在冲突。这不是冲突。有布尔意义。考虑一些算法给我DF1和另一个给出DF2。我想对df1和df2使用逻辑OR。对于6.txt,那么我有True或False,它在结果df中应该是True。问题是:如果值是布尔值,如何处理数据帧。如何执行逻辑操作?在我的特例中,数据帧有不同的形状。如何以这种特殊的方式处理。如何防止类型更改?
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