0

Using python, I've created a dataframe with a datetime index.

datetime_index = pd.date_range(start='2018-01-01', end='2019-12-31', freq='D')
df = pd.DataFrame({}, index=datetime_index)

Now I would like to be able to search through a list of dates, if the date in index is also in the list I've created, I would like a new variable df['fireworks'] to be 1, otherwise 0. I have tried creating a list like this:

fireworks = {'2018-07-04', '2018-07-05', '2018-04-13', '2018-04-18'}

I tried to accomplish this way:

df['fireworks'] = np.where(df.index==fireworks, 1, 0)

All the values of the newly created df['fireworks'] are still 0.

Thanks in advance to anyone helping me with this.

1 Answer 1

2

Use Series.isin:

datetime_index = pd.date_range(start='2018-01-01', end='2019-12-31', freq='D')
df = pd.DataFrame({}, index=datetime_index)

fireworks = {'2018-07-04', '2018-07-05', '2018-04-13', '2018-04-18'}

df['fireworks'] = np.where(df.index.isin(fireworks), 1, 0)

print (df[df["fireworks"].eq(1)])

#
            fireworks
2018-04-13          1
2018-04-18          1
2018-07-04          1
2018-07-05          1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.