Skip to content

Repository files navigation

log-count-utils

Introduction & Usage

Suppose we have an action log data df like

user_idtimestampexpense
02021-02-18 10:00:00100
02021-02-18 10:00:1010
02021-02-18 10:00:211
02021-02-18 11:00:210.1
12020-02-18 10:00:10100
12020-02-18 10:00:2010
12020-02-18 10:00:201
12020-02-18 10:00:290

Suppose that you have to compute the following quantity for each row in this dataframe:

  • the number of actions each user has taken within 10 seconds
  • total amount of expenses of a user within 10 seconds

The following naive way is fine for this tiny example but becomes costly (O(N^2)) for large data frame.

fromdatetimeimporttimedeltaimportnumpyasnptd=timedelta(seconds=10)
answers= []
foruid, time_pointinzip(df.user_id, df.timestamp):
cnt=np.sum(
(df.user_id==uid) & (df.timestamp<time_point) & (df.timestamp>= (time_point-td))
)
answers.append(cnt)

If df is sorted (by user_id as the primary and timestamp as the secondary key), we can do this blazing fast (O(N)) using log_count_util.

fromlog_count_utilimportfind_n_records_within_intervalanswers=find_n_records_within_interval(
df.user_id, df.timestamp, df_user_id, df.timestamp, td
)

About

A utility module to count/aggregate logs within a time interval

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages