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 ]
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
You might use numpy.logical_and
and numpy.logical_or
for this task, ie:
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.