Wednesday, 16 September 2020

How to group a dataframe by 4 time periods and key

I have a dataset that looks something like this,

Startdtm    HostName_key    Totalvehicles   Enddtm  starthour   timedelta   vehiclespersec
2020-01-15 08:22:39 0   9603    2020-01-15 16:32:39 8   29400.0 0.32663265306122446
2020-01-13 08:22:07 0   10273   2020-01-13 16:25:08 8   28981.0 0.35447362064801075
2020-01-23 07:16:55 3   5175    2020-01-23 14:32:44 7   26149.0 0.19790431756472524
2020-01-15 07:00:06 1   838 2020-01-15 07:46:29 7   2783.0  0.3011139058569889
2020-01-15 08:16:01 1   5840    2020-01-15 12:41:16 8   15915.0 0.3669494187873076

That is then being computed into this to create a kmeans cluster.

def cluster_Volume(inputData):

    start_tot = time.time()
    Volume = inputData.groupby(['Startdtm','DetectionTypes'])['vehiclespersec'].sum().unstack()


    ## 4 Clusters

    model = clstr.MiniBatchKMeans(n_clusters=5)
    model.fit(Volume.fillna(0))
    Volume['kmeans_4'] = model.predict(Volume.fillna(0))
    end_tot = time.time()
    print("Completed in " + str(end_tot-start_tot))



    ## 8 Clusters

    start_tot = time.time()
    model = clstr.KMeans(n_clusters=8)
    model.fit(Volume.fillna(0))
    Volume['kmeans_8'] = model.predict(Volume.fillna(0))
    end_tot = time.time()
    print("Completed in " + str(end_tot-start_tot))

    ## Looking at hourly distribution.
    start_tot = time.time()
    Volume_Hourly = Volume.reset_index().set_index(['Startdtm'])

    Volume_Hourly['hour'] = Volume_Hourly.index.hour
    end_tot = time.time()
    print("Completed in " + str(end_tot-start_tot))




    return Volume, Volume_Hourly

What I want to do is to make those clusters relate to both time periods and keys.

WIth the time periods - 7am to 10am, and 4pm to 6pm, and 12pm to 2pm, with 6pm to 12am, 12am to 7am, and 10am to 12pm, 2pm to 4pm as other time periods.

And with the keys - showing how each cluster differently in a programmatic way.

Desired Result

The Desired result will have a table similar to below, but feel free to develop it in the best way you can think of. Time period meaning, say 1 would be before 6am, 2 6am to 9am, 3 9 to 11, 4 11 to 14, etc.. but feel free to change it as suits - just my thoughts

Startdtm    Volume Time_period  kmeans_4    kmeans_8    hour    location 

I've tried a few approaches to this using groupby, but it doesn't seem to work super well - would love some guidance here.



from How to group a dataframe by 4 time periods and key

No comments:

Post a Comment