Home > Back-end >  Pandas filter datetime column by time frequency
Pandas filter datetime column by time frequency

Time:06-15

title may be a bit confusing. What I mean is, let's say I have a df like:

date (dd/mm/yyyy) value
01/01/2000 w
02/01/2000 x
[...] [...]
31/12/2009 y
01/01/2010 z

And I want to filter it by three different time frequencies: day, month and year. It's already filtered by day, so 'month' would look like:

date (dd/mm/yyyy) value
01/01/2000 w
01/02/2000 a
01/03/2000 b
01/04/2000 c
[...] [...]

And 'year':

date (dd/mm/yyyy) value
01/01/2000 w
01/01/2001 e
01/01/2002 f
01/01/2003 g
[...] [...]

CodePudding user response:

I think I have a better understanding for which you are asking. I had to create my own pandas date column, but the concept is there for you to work with just replace with your own columns

df_dates = pd.DataFrame(pd.date_range('01-01-2000', '12-31-2004', freq = 'd'), columns = ['Dates'])
start_date = '2001-02-25'
end_date = '2004-03-21'
df_dates.loc[
    (df_dates['Dates'].between(start_date, end_date)) 
    & 
    (df_dates['Dates'].dt.day.eq(25))
]

The downside of this is that it is not very flexible because you will need to manually update your code to have the configuration you would need. However, this should give you the results you are expecting AND you can take this and make a function that would make it easier to use (Making a function that will accept a couple inputs and handle the & statements is probably what I would do in this situation)

  • Related