r/learnpython • u/Dragoran21 • 15m ago
Hot write "Not A, unless B" in Boolean Algebra?
I have a rather complex row selection mission at hand.
To select the rows I want, I have to use two lists of keywords. One contains words that I want (kw_Y), and the other contains words I don't want (kw_N). I originally used this simply to collect the rows that have the wanted information, but now I need to do some comparison analysis with rest of the data.
I need to select rows "that don't have the kw_Y terms, unless they have kw_N terms". Or as Google put it: "No A unless B" (meaning A is false except when B is true) translates to ¬A unless B, or ¬A ∨ B (logically equivalent to B → A, "if B then A").
Boolean logic has never been my strongest point. What would this be in Python?
Codes:
good_stuff = dataframe[kw_Y & ~kw_N] #Yes these masks, not just lists. Algebra is the focus.
bad_stuff = dataframe[kw_N & ~kw_Y] #didn't select enough rows
bad_stuff2 = dataframe[~kw_Y] #I realized this removes rows that contain stuff I now want.
all_bad_stuff = dataframe[???]
•
u/ExpertSentence4171 10m ago
Didn't you say it yourself? [~kw_Y or kw_N]? Maybe I'm misunderstanding the problem here
•
u/jameyiguess 10m ago
Isn't that just A and B
•
u/Free-Good9203 3m ago
Since you want the exact "rest of the data" (everything not in `good_stuff`), De Morgan's law makes this super clean:
The opposite of `kw_Y & ~kw_N` is `~kw_Y | kw_N` (use bitwise `|`, not `or`, since these are pandas boolean masks—`or` will throw an ambiguous truth value error).
Honestly though, the easiest way to avoid messing up the algebra (and guarantee zero overlap or dropped rows) is to just store the mask once and invert it:
is_good = kw_Y & ~kw_N
good_stuff = dataframe[is_good]
all_bad_stuff = dataframe[~is_good] # exact same result as dataframe[~kw_Y | kw_N]
If you want to double-check, `len(good_stuff) + len(all_bad_stuff) == len(dataframe)` will always be `True` (assuming no `NaN`s in the masks).