Python 在日期之间更改系列中的值
我有一个熊猫系列,它的每日条目都设置为False:Python 在日期之间更改系列中的值,python,numpy,pandas,scipy,Python,Numpy,Pandas,Scipy,我有一个熊猫系列,它的每日条目都设置为False: d = pd.Series(False, pd.bdate_range("20100101", periods=100, freq="D")) 现在,我想将每个月15日和20日之间的值设置为True。我生成了一个系列,其中索引为开始/结束日期和真值: s = pd.Series(True, pd.bdate_range("20100101", periods=100, freq="MS") + pd.DateOffset(14)) e = p
d = pd.Series(False, pd.bdate_range("20100101", periods=100, freq="D"))
现在,我想将每个月15日和20日之间的值设置为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))
此时,s和e将包含开始日期和结束日期,我希望将d中的值设置为True。我不知道该如何优雅地将此应用于d
该问题的一个复杂情况是,如果s和e是随机的,也就是说,它并不总是每月的15-20天:
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))
您可以使用,但首先需要使用以下内容创建系列:
您可以使用,但首先需要使用以下内容创建系列:
使用现有的pd.Series,您可以通过DateTimeIndex的.day属性使用,或者使用np.INAD来达到相同的效果:
d[(d.index.day >= 15) & (d.index.day <= 20)] = True
d[np.in1d(d.index.day, np.arange(15, 20))] = True
使用现有的pd.Series,您可以通过DateTimeIndex的.day属性使用,或者使用np.INAD来达到相同的效果:
d[(d.index.day >= 15) & (d.index.day <= 20)] = True
d[np.in1d(d.index.day, np.arange(15, 20))] = True
谢谢-以上的作品。如果s和e不是很规则,即s和e作为输入,并且对s[i],e[i]可以是任何给定s[i]
d[(d.index.day >= 15) & (d.index.day <= 20)] = True
d[np.in1d(d.index.day, np.arange(15, 20))] = True
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