r/learnpython • u/Dragoran21 • 2d 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[???]
10
u/Free-Good9203 2d 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).
7
u/ExpertSentence4171 2d ago
Didn't you say it yourself? [~kw_Y or kw_N]? Maybe I'm misunderstanding the problem here
5
u/Mandelbrots-dream 2d ago
I believe you'll need
(not A) or B
Here's the truth table:
1
u/kilkil 2d ago
using the word "unless" might be adding extra confusion here. the typically accepted term is "or". so what you are looking for is "(not A) or B". that's actually how you write it in Python directly:
now in your code snippets you're using bitwise operators for some reason. Assuming this is intended, and you understand the difference between bitwise operators and boolean operators, you would also write it the same way (not A or B):
5
u/jameyiguess 2d ago
Isn't that just A and B
2
u/Some-Passenger4219 2d ago
Make a table. One row for A & B both true, one for both false, one for A only, one for B only. Which gives you the results you want? Compare it to the ops you already know.
1
u/pythonwiz 1d ago
I suggest restating that as “unless b, a”; then make a truth table, fill out the entries, and compare to other binary operators. That should make it clear. You could also try other ways of restating that in English and see if anything clicks for you.