Home > database >  Merge multiple Boolean data frames into one data frame based on Boolean values
Merge multiple Boolean data frames into one data frame based on Boolean values

Time:07-20

I have three Boolean data frames which are part of the same dictionary. I would like to have as an output one data frame, containing all the true rows. So if one row is True in one of the data frames it's True in the output dataframe. if it's False in All data frames, it's False in the output dataframe.

data1 ={"":[True,False,True,False,False]}
data2= {"":[False,True,False,False,False]}
data3= {"":[False,False,False,False,True]}

df1=pd.DataFrame(data1)
df2=pd.DataFrame(data2)
df3=pd.DataFrame(data3)

Expected output:

Output_Data= {"":[True,True,True,False,True]}

CodePudding user response:

IIUC, you can concat all dataframes on columns and use any(axis=1)

out = pd.concat([df1, df2, df3], axis=1).any(axis=1)
print(out)

0     True
1     True
2     True
3    False
4     True
dtype: bool

print({'': out.tolist()})

{'': [True, True, True, False, True]}

CodePudding user response:

You can use or on multiple DataFrame then convert to the desired dictionary with pandas.to_dict like below.

>>> (df1 | df2 | df3).to_dict('list')
{'': [True, True, True, False, True]}
  • Related