I have a pandas Series() which has daily entries all set to False:
d = pd.Series(False, pd.bdate_range("20100101", periods=100, freq="D"))
I now want to set the values between the 15th and 20th of each month to True. I generate a Series with indices being the start/end dates and values of True:
s = pd.Series(True, pd.bdate_range("20100101", periods=100, freq="MS") + pd.DateOffset(14))
e = pd.Series(True, pd.bdate_range("20100101", periods=100, freq="MS") + pd.DateOffset(19))
At this point s
and e
will contain the start and end dates between which I want to set the values in d
to True. I am not sure how to apply this to d
elegantly.
A complication to this problem is if s and e are random (i.e. it is not always the 15-20 day of the month):
import random
sd = random.choice([1,2,3,4])
ed = random.choice([1,2,3,4]) + sd
del sd
del ed
# The delay is still constant for the entire series and not random per row
s = pd.Series(True, pd.bdate_range("20100101", periods=100, freq="MS") + pd.DateOffset(14 + sd))
e = pd.Series(True, pd.bdate_range("20100101", periods=100, freq="MS") + pd.DateOffset(19 + ed))
Using your existing pd.Series
, you can use boolean indexing
via the .day
attribute of the DateTimeIndex
, or use np.in1d
to the same effect:
d[(d.index.day >= 15) & (d.index.day <= 20)] = True
d[np.in1d(d.index.day, np.arange(15, 20))] = True
both resulting in:
2010-01-01 False
2010-01-02 False
2010-01-03 False
2010-01-04 False
2010-01-05 False
2010-01-06 False
2010-01-07 False
2010-01-08 False
2010-01-09 False
2010-01-10 False
2010-01-11 False
2010-01-12 False
2010-01-13 False
2010-01-14 False
2010-01-15 True
2010-01-16 True
2010-01-17 True
2010-01-18 True
2010-01-19 True
2010-01-20 True
2010-01-21 False
2010-01-22 False
2010-01-23 False
2010-01-24 False
2010-01-25 False
2010-01-26 False
2010-01-27 False
2010-01-28 False
2010-01-29 False
2010-01-30 False
...
2010-03-12 False
2010-03-13 False
2010-03-14 False
2010-03-15 True
2010-03-16 True
2010-03-17 True
2010-03-18 True
2010-03-19 True
2010-03-20 True
2010-03-21 False
2010-03-22 False
2010-03-23 False
2010-03-24 False
2010-03-25 False
2010-03-26 False
2010-03-27 False
2010-03-28 False
2010-03-29 False
2010-03-30 False
2010-03-31 False
2010-04-01 False
2010-04-02 False
2010-04-03 False
2010-04-04 False
2010-04-05 False
2010-04-06 False
2010-04-07 False
2010-04-08 False
2010-04-09 False
2010-04-10 False
Freq: D, dtype: bool
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments