r/learnpython • u/blackgarliccookie • 20m ago
Turning 19 boolean variables into 1.
I'm back again, hopefully with clearer information.
I have 19 boolean variables. Each one is labeled with the date of an election. Inside the variable has true/false. True is voted, False is didn't vote.
I want to create a voting history variable that has a few options.
Never voted, if all 19 are false.
Voted in the past 5 years, if any of the date variables in the past 5 years, aside from the recent midterm, have a vote.
Voted in the past 10 years, if no votes were cast in the past 5 but there were votes in the past 10.
And recently registered, which would involve the registration_dt variable which I feel more confident being able to implement.
I just really don't know how to turn these into one variable without losing information. Thanks so much :)
•
u/white-9igga 0m ago
you wont actually lose info here, because your categories are in an order of priority (never voted, then voted in last 5, then last 10 and so on) so the first one that matches wins and the rest dont matter.
easiest way, split your 19 columns into two lists by date, one for the last 5 years (leaving out the recent midterm like you said) and one for the last 10. then make a few true/false checks, like voted5 = df[last5cols].any(axis=1), voted10 = df[last10cols].any(axis=1), never = not df[allcols].any(axis=1). then use np.select with the conditions in order (never first, then voted5, then voted10) and a default for anything else, and it gives you one column with the label for each row.
the recently registered one you can do the same way, just add it as another condition and decide where it sits in the order, since someone can be registered recently and also never voted, so pick which label should win :)