In Python Pandas. How to multiply DataFrame WOM - "Week of the month"?

I want to be able to subset df by week of the month, similar to what you can do with the day of the week or month.

sample = df[df.index.month == 12] 

      

So, is there a way to do this?

sample = df[df.index.WOM == 1]

      

I know that if I type the line above, you get an AttributeError: the "Index" object has no "WOM" attribute, just for reference to understand what I want to do.

thank

+3


source to share


1 answer


You can look at the value .weekofyear

and the same value at the beginning of the month, and the difference between the two should give the week of the month; eg:

>>> days = ['2014-02-01', '2014-06-10', '2014-08-30', '2014-11-22']
>>> idx = pd.to_datetime(days)
>>> idx.weekofyear
array([ 5, 24, 35, 47], dtype=int32)

      

at the beginning of the month, you can subtract .day

from the index itself:



>>> mon = idx - pd.to_timedelta(idx.day - 1, unit='D')
>>> mon.weekofyear
array([ 5, 22, 31, 44], dtype=int32)

      

and week of the month:

>>> 1 + idx.weekofyear - mon.weekofyear
array([1, 3, 5, 4], dtype=int32)

      

+4


source







All Articles