Pandas groupby week given a datetime column

2024/9/23 21:30:32

Let's say I have the following data sample:

df = pd.DataFrame({'date':['2011-01-01','2011-01-02','2011-01-03','2011-01-04','2011-01-05','2011-01-06','2011-01-07','2011-01-08','2011-01-09','2011-12-30','2011-12-31'],'revenue':[5,3,2,10,12,2,1,0,6,10,12]})# Let's format the date and add the week number and year
df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d')
df['week_number'] = df['date'].dt.week
df['year'] = df['date'].dt.yeardfdate        revenue     week_of_year    year
0       2011-01-01  5           52              2011
1       2011-01-02  3           52              2011
2       2011-01-03  2           1               2011
3       2011-01-04  10          1               2011
4       2011-01-05  12          1               2011
5       2011-01-06  2           1               2011
6       2011-01-07  1           1               2011
7       2011-01-08  0           1               2011
8       2011-01-09  6           1               2011
9       2011-12-30  10          52              2011
10      2011-12-31  12          52              2011

I would like to compute the revenue per week, in order to later plot the results, and analyze the time series. The expected output would then be something like that :

    week    revenue
0   1       8
1   2       33
2   52      22

I first thought of using the week number given by timestamp.week.
However, I can't figure out how to deal with the ISO week number definition for the week preceeding week number 1. I am a bit confused, since grouping by week_number would in that case sum both the revenue at the very beginning of the year, and those at the end of the year.

Answer

When you convert using dt.week , it is ISO week date.

You can using strftime

df.groupby(df.date.dt.strftime('%W')).revenue.sum()
Out[588]: 
date
00     8
01    33
52    22
Name: revenue, dtype: int64
https://en.xdnf.cn/q/71779.html

Related Q&A

Django form to indicate input type

Another basic question Im afraid which Im struggling with. Ive been through the various Django documentation pages and also search this site. The only thing I have found on here was back in 2013 which…

run multi command in the same jupyter cells

Im trying to display 2 output of 2 lines in the same time, I use Panda library and it seems like it display only the output of second line:import pandas as pd data = {"state": ["Ohio&quo…

Pandas how to get rows with consecutive dates and sales more than 1000?

I have a data frame called df: Date Sales 01/01/2020 812 02/01/2020 981 03/01/2020 923 04/01/2020 1033 05/01/2020 988 ... ...How can I get the first occurrence of 7 conse…

Use Python alongside C# in Windows UWP app

I started writing an application in Python, but I now want to switch to C# and UWP. I know that you cannot write a UWP app in Python, but I am trying to see if I can write some code in Python and acces…

How do you go from a sip.voidptr (QImage.constBits()) to a ctypes void or char pointer?

Im using python and of course you cant loop through every pixel of a large image very quickly, so I defer to a C DLL.I want to do something like this:img = QImage("myimage.png").constBits() i…

Just returning the text of elements in xpath (python / lxml)

I have an XML structure like this:mytree = """ <path><to><nodes><info>1</info><info>2</info><info>3</info></nodes></to> …

Python function parameter: tuple/list

My function expects a list or a tuple as a parameter. It doesnt really care which it is, all it does is pass it to another function that accepts either a list or tuple:def func(arg): # arg is tuple or …

Python binding for C++ operator overloading

I have a class similar to the following:class A {vector<double> v;double& x(int i) { return v[2*i]; }double& y(int i) { return v[2*i+1]; }double x(int i) const { return v[2*i]; }double y(…

python script to pickle entire environment

Im working inside the Python REPL, and I want to save my work periodically. Does anybody have a script to dump all the variables I have defined? Im looking for something like this:for o in dir():f=ope…

django-endless with class based views example

Im using Class Based Views for the first time. Im having trouble understating how using class based views I would implement django-endless-pagination twitter styling paging.Could I have an example of h…