Home > Software design >  PANDAS: AND and OR between two dataframes
PANDAS: AND and OR between two dataframes

Time:10-29

I have two dataframes of the same size with boolean values. Is there a way to perform the AND, OR or XOR functions between the two dataframes?

for example

df1:

[False, True, False]  
[True,  False, True]   

df2:

[True, False, False]      
[True, False, False]

df1 OR df2

[True, True, False]
[True, False,True ]

CodePudding user response:

IIUC, You can use .tolist() then get what you want like below:

>>> df1 = pd.DataFrame({'col1': [False, True, False],'col2': [True,  False, True]})

>>> df2 = pd.DataFrame({'col1': [True, False, False],'col2': [True, False, False]})

>>> (df1 | df2)['col1'].tolist()
[True, True, False]

>>> (df1 | df2)['col2'].tolist()
[True, False, True]

>>> (df1 | df2)
    col1    col2
0   True    True
1   True    False
2   False   True

CodePudding user response:

You might use numpy.logical_and and numpy.logical_or for this task, i.e.:

import numpy as np
import pandas as pd
df1 = pd.DataFrame([[False,True,False],[True,False,True]])
df2 = pd.DataFrame([[True,False,False],[True,False,False]])
dfor = np.logical_or(df1,df2)
print(dfor)

output

      0      1      2
0  True   True  False
1  True  False   True

CodePudding user response:

df1 = pandas.DataFrame({1: [False, True, False], 2: [True,  False, True]})
df2 = pandas.DataFrame({1: [True, False, False], 2: [True, False, False]})

Using OR:

resulting_dataframe_using_OR = pandas.DataFrame({1: (df1[1]|df2[1]), 2: (df1[2]|df2[2])})

Output using OR:

       1      2
0   True   True
1   True  False
2  False   True

Using AND:

resulting_dataframe_using_AND = pandas.DataFrame({1: (df1[1]&df2[1]), 2: (df1[2]&df2[2])})

Output using AND:

       1      2
0  False   True
1  False  False
2  False  False
  • Related