Emac
Emac

Reputation: 1167

If row contains date, get value of other cell

I am trying to iterate through rows in a Pandas dataframe and check if the date equals a specific date, and if it does, return the value of another cell. I figured I could create a mask to do this and then use np.where to assign True or False to those rows. I have done this in the past using strings and integers, but now that it is using a date it is not working.

If I do:

df[pd.to_datetime(df['birth_date']) == '1990-12-10']

It returns the row of the person whose birth_date is that day.

However, if I do:

for index, row in df.iterrows(): 
    bday_mask = (pd.to_datetime(row['birth_date']) == '1990-12-10')
    df['bday_is_today'] = np.where(bday_mask, True, False)

It assigns every row to "False". How do I put a flag on rows if their birth date is equal to that date?

Upvotes: 1

Views: 613

Answers (1)

petezurich
petezurich

Reputation: 10184

You don't neep to iterate, just get the indices of all rows where your condition is true:

df["bday_is_today"] = False
bdays = df[pd.to_datetime(df['birth_date']) == '1990-12-10'].index
df.loc[bdays, 'bday_is_today'] = True

Upvotes: 1

Related Questions