Suppose I have a bool DataFrame df
and a bool Series x
with the same index, and I want to do logical operation between df
and x
per column. Is there any short and fast way like DataFrame.sub
compare to using DataFrame.apply
?
In [31]: df
Out[31]:
x y z u
A False False True True
B True True True True
C True False False False
In [32]: x
Out[32]:
A True
B False
C True
dtype: bool
In [33]: r = df.apply(lambda col: col & x) # Any other way ??
In [34]: r
Out[34]:
x y z u
A False False True True
B False False False False
C True False False False
Use mul
, but need cast to int
and then to bool
, because UserWarning
:
print (df.astype(int).mul(x.values, axis=0).astype(bool))
x y z u
A False False True True
B False False False False
C True False False False
Similar solution:
print (df.mul(x.astype(int), axis=0).astype(bool))
x y z u
A False False True True
B False False False False
C True False False False
print (df.mul(x.values, axis=0))
x y z u
A False False True True
B False False False False
C True False False False
C:\\Anaconda3\\lib\\site-packages\\pandas\\computation\\expressions.py:181: UserWarning: evaluating in Python space because the '*' operator is not supported by numexpr for the bool dtype, use '&' instead unsupported[op_str]))
Another numpy
solution with np.logical_and
:
print (pd.DataFrame(np.logical_and(df.values, x.values[:, None]),
index=df.index,
columns=df.columns))
x y z u
A False False True True
B False False False False
C True False 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.