-1

I do wonder how it is possible to make sliding windows in Pandas. I have a dataframe with three columns.

Country | Number | DayOfTheYear
===================================
No      | 50     | 0
No      | 20     | 1
No      | 37     | 2

I would love to see 14 day chunks for every country and day combination. The country think can be ignored for the moment, since I can filter those manually in some way. But imagine there is only one country, is there a smart way to get some sort of summed up sliding window, resulting in something like the following?

Country | Sum | DatesOftheYear
===================================
No      | 504     | 0-13
No      | 207     | 1-14
No      | 337     | 2-15

I would also accept if if they where disjunct, being only 0-13, 14-27, etc. But I just cannot come along with Pandas. I know an old SQL solution, but is there anybody having a nice idea for Pandas?

Hemmelig
  • 803
  • 10
  • 22

1 Answers1

1

If you want a rolling windows of your dataframe, you can simply use the .rolling function of pandas : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html

In your case : df["Number"].rolling(14).sum()

Erlinska
  • 433
  • 5
  • 16
  • I see, it actually works. The only thing which seems weird is how it summed up the dayOfTheYearThings as well. I mean, the numbers are correct, but those columns are looking quite weird. Is there a clever way to let them stay as they are, not being summed up? – Hemmelig Jun 22 '21 at 10:13
  • I'm not sure I 100% understand your question, but the rolling function will only work for your number column in the way you expect. To create the `DatesOftheYear` column you can for example do the following: `df["Days"].shift(13).astype(str) + "-" + df["Days"].astype(str)` – Erlinska Jun 22 '21 at 10:23
  • Ah, nevermind. I just found out that I did a mistake in using the command. It works totally fine now :) – Hemmelig Jun 22 '21 at 10:27