Home > Software engineering >  Boolean comparaison between a series and a dataframe (element-wise)
Boolean comparaison between a series and a dataframe (element-wise)

Time:10-14

Here the series and dataframe to be compared element-wise (AND condition):

import pandas as pd

se = pd.Series(data=[False, True])

df = pd.DataFrame(data=[[True, False], [True, True]],
                  columns=['A','B'])

Desired result:

df2 = pd.DataFrame(data=[[False, False], [True, True]],
                  columns=['A','B'])

I could achieve that using a slow for loop but I am sure there is a way to vectorise that.

Many thanks !

CodePudding user response:

Convert Series to numpy array and compare with broadcasting:

print (df & se.to_numpy()[:,None])
       A      B
0  False  False
1   True   True

CodePudding user response:

You can use conversion to numpy array to benefit from broadcasting:

out = np.logical_and(df, se.to_numpy()[:,None])

output:

       A      B
0  False  False
1   True   True

intermediate:

se.to_numpy()[:,None]

array([[False],
       [ True]])

CodePudding user response:

Another possible solution:

(df & np.vstack(se))

Output:

       A      B
0  False  False
1   True   True
  • Related