python - 在日期之间更改 Pandas 系列中的值

标签 python numpy pandas scipy

我有一个 pandas Series(),它的每日条目都设置为 False:

d = pd.Series(False, pd.bdate_range("20100101", periods=100, freq="D"))

我现在想将每个月的 15 日到 20 日之间的值设置为 True。我生成一个系列,其中索引是开始/结束日期和 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))

此时 se 将包含我想要的 start 和 end 日期将 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,您可以使用 boolean indexing通过 DateTimeIndex.day 属性,或使用 np.in1d 达到同样的效果:

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

关于python - 在日期之间更改 Pandas 系列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37811420/

相关文章:

python - 当每一行都是一个列表时,如何使用 pandas isin() 函数?

python - python中数学函数的优化和加速

python - 使用 Numpy Convolve 时幅度发生变化

python - 如何在Python 3中避免 "no module installed"

python - 在python中转置数据

Python Numpy 数组相等失败

python - 应用以属性系列作为参数的函数

python - 有没有办法用 pandas.read_excel() 加载带有特定正则表达式的工作表

python - 单击终端中的元素

python - 使用系列查找表替换 Pandas DataFrame 列中的值