1

How do I set the value for a certain date range in every year e.g 20 March - 15 July? I've tried using the code below to set all values before 20 April to 0 but as you can see it only sets the values before the 20th of each month to 0

idx = pd.date_range(dt.date(2010,1,1) , dt.date(2020,1,1) , freq = 'd')
df = pd.DataFrame(data = np.random.randint(0,5, size=len(idx)),index = idx )

df.loc[(df.index.month <= 4) & (df.index.day <20)] = 0
df.head(50)

enter image description here

KaneM
  • 259
  • 2
  • 9
  • Another period that I found difficulty in solving is when the period crosses a year e.g How do I set all values from 10th December to 15th January to 0? – KaneM Jan 12 '22 at 09:25
  • 1
    related : [Selecting Pandas DataFrame records for many years based on month & day range](https://stackoverflow.com/q/18746650/10197418) – FObersteiner Jan 12 '22 at 10:08
  • Thanks , that solves it – KaneM Jan 12 '22 at 10:16
  • great, I'd vote to close as duplicate; you could keep the question anyway if you want for people landing here and find the other question(s). – FObersteiner Jan 12 '22 at 10:20
  • Does this answer your question? [Selecting Pandas DataFrame records for many years based on month & day range](https://stackoverflow.com/questions/18746650/selecting-pandas-dataframe-records-for-many-years-based-on-month-day-range) - or [Subset Pandas DataFrame based on annual returning period covering multiple months](https://stackoverflow.com/q/45996397/10197418) – FObersteiner Jan 12 '22 at 10:20

0 Answers0