Skip to content Skip to sidebar Skip to footer

Python: Filter DataFrame In Pandas By Hour, Day And Month Grouped By Year

Being new to Pandas I had to dig a lot in order to find a solution to this problem. I would like to know a better way to get this resolved, taking into account I still need to reso

Solution 1:

Updated code for filter function ensures there is no border issues:

import pandas as pd
import numpy as np
import datetime

dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="10min")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])

def filter(df, day, month, hour, minute=0, daysWindow=1, hoursWindow=1):
    """
    Filter a Dataframe by a date window and hour window grouped by years

    @type df: DataFrame
    @param df: DataFrame with dates and values

    @type day: int
    @param day: Day to focus on

    @type month: int
    @param month: Month to focus on

    @type hour: int
    @param hour: Hour to focus on

    @type daysWindow: int
    @param daysWindow: Number of days to perform the days window selection

    @type hoursWindow: int
    @param hourWindow: Number of hours to perform the hours window selection

    @rtype: DataFrame
    @return: Returns a DataFrame with the
    """
    df_filtered = None
    grouped = df.groupby(lambda x : x.year)
    for year, groupYear in grouped:
        date = datetime.date(year, month, day)
        dateStart = date - datetime.timedelta(days=daysWindow)
        dateEnd = date + datetime.timedelta(days=daysWindow+1)
        df_filtered_days = df[dateStart:dateEnd]
        timeStart = datetime.time(0 if hour-hoursWindow < 0 else hour-hoursWindow, minute)
        timeEnd = datetime.time(23 if hour+hoursWindow > 23 else hour+hoursWindow, minute)
        new_df = df_filtered_days.ix[df_filtered_days.index.indexer_between_time(timeStart, timeEnd)]
        if df_filtered is None:
            df_filtered = new_df
        else:
            df_filtered = df_filtered.append(new_df)
    return df_filtered

df_filtered = filter(df,day=8, month=10, hour=1, daysWindow=1, hoursWindow=2)
print len(df)
print len(df_filtered)

Output is:

>>> 
157825
174

Post a Comment for "Python: Filter DataFrame In Pandas By Hour, Day And Month Grouped By Year"