r/learnpython • • 4h 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.

Here is my code & the data.

I just really don't know how to turn these into one variable without losing information. Thanks so much :)

3 Upvotes

11 comments sorted by

3

u/white-9igga 4h 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 :)

1

u/blackgarliccookie 2h ago

Ahh ok this sounds doable, I will give this a shot tomorrow and try & tell how it goes.

2

u/FainourSpreitzer52 3h ago

are these actually 19 standalone variables in a script, or columns in a table/CSV? if theyre standalone variables, id throw them into a dict first so you can iterate over the dates instead of hardcoding every single check.

1

u/blackgarliccookie 3h ago

They are columns but this is for school so I can't really do that :(

1

u/Penguinase 4h ago

if i understand you correctly then you could create a helper column like last_vote_date then derive those filters/labels from it.

for example

vote_cols = [c for c in wakevote.columns if c.endswith('_V')]   # should be 19 cols

votes = wakevote[vote_cols].fillna(False).astype(bool)
votes.columns = pd.to_datetime(votes.columns.str.removesuffix('_V'), format='%m/%d/%Y')
votes = votes.sort_index(axis=1)        # oldest first
dates = votes.columns                   # dates from the parsedcolumns

wakevote['n_votes'] = votes.sum(axis=1)
wakevote['last_vote_date'] = (
    votes.astype(int).iloc[:, ::-1].idxmax(axis=1)   # newest True  date per row
    .where(wakevote['n_votes'] > 0)                  # nan if never voted
)

1

u/Kevdog824_ 3h ago

I am not sure I understand your question, or the format of your data, but I will give it my best. For simplicity,I am going to assume your data is in the form of a dictionary mapping the date objects to the list of True/False values under those dates named vote_history (kinda like the second image in your linked post). Looks like in screenshot 1 you might be using pandas so not sure this will translate but this should give you the general logic for this (assuming I actually understand your goal)

Never voted, if all 19 are false.

from datetime import date


type VoteHistory = dict[date, list[bool]]


def never_voted(vote_history: VoteHistory) -> bool:
    return all((not vote for votes in vote_history.values() for vote in votes))

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.

from datetime import date


type VoteHistory = dict[date, list[bool]]


def voted_in_past_5_years(vote_history: VoteHistory) -> bool:
    today = date.today()
    five_years_ago = today.replace(year=today.year - 5)
    filtered_elections = {d: v for d, v in vote_history.items() if d >= five_years_ago}
    return any((vote for votes in filtered_elections.values() for vote in votes))

Voted in the past 10 years, if no votes were cast in the past 5 but there were votes in the past 10.

from datetime import date


type VoteHistory = dict[date, list[bool]]


def voted_in_past_5_to_10_years(vote_history: VoteHistory) -> bool:
    today = date.today()
    five_years_ago = today.replace(year=today.year - 5)
    ten_years_ago = today.replace(year=today.year - 10)
    filtered_elections = {d: v for d, v in vote_history.items() if d < five_years_ago and d >= ten_years_ago}
    not_voted_in_past_five = not voted_in_past_5_years(vote_history)  # From previous section
    return any((vote for votes in filtered_elections.values() for vote in votes)) and not_voted_in_past_five

1

u/4Floaters 3h ago

You are looking for a bit mask

1

u/igotshadowbaned 1h ago

True = 1 and False = 0, you can use this to your advantage

If you have a list of your voting results called "voted"

if sum(voted) == 0:

Would return true if all 19 values in the list are false

If you want to just take a look at a certain few, you can use slices

if sum(voted[-5:]) != 0:

Would return true if any of the last 5 items in the list are true

1

u/[deleted] 3h ago

[removed] — view removed comment

1

u/avalexva 3h ago

I,m think any like this

vote_cols = [c for c in wakevote.columns if c.endswith("_V")]
col_dates = {c: pd.to_datetime(c[:-2], format="%m/%d/%Y") for c in vote_cols}

cols_5y  = [c for c, d in col_dates.items()
            if today - pd.DateOffset(years=5) <= d and d != recent_midterm]
cols_10y = [c for c, d in col_dates.items()
            if today - pd.DateOffset(years=10) <= d < today - pd.DateOffset(years=5)]

voted_5y  = wakevote[cols_5y].any(axis=1)
voted_10y = wakevote[cols_10y].any(axis=1)
voted_any = wakevote[vote_cols].any(axis=1)