Using the Pandas API for Python, for each timestamp, I want to calculate the number of unique devices seen in an account in the last 48 hours from each of the timestamps.
This is what my data looks like:
╔═════════════════════╦══════════╦═══════════╗
║ timestamp ║ device ║ accountid ║
╠═════════════════════╬══════════╬═══════════╣
║ 2018-10-29 18:52:30 ║ d1ed6e6 ║ DhHUXPw ║
║ 2018-11-01 18:52:30 ║ d123ff96 ║ zgffRDY ║
║ 2018-11-01 20:53:30 ║ e322ff96 ║ zgffRDY ║
║ 2018-11-02 21:33:30 ║ g133gf42 ║ zgffRDY ║
║ 2018-11-15 18:52:30 ║ d123ff96 ║ awfdsct ║
║ 2018-11-17 08:25:30 ║ d123ff96 ║ awfdsct ║
╚═════════════════════╩══════════╩═══════════╝
I except the output to look like this. Essentially, for account zgffRDY
at 2018-11-02 21:33:30
, we have seen 3
unique devices in the last 48 hours, whereas at 2018-11-01 18:52:30
, we have only seen 1
device (being the current device)
╔═════════════════════╦══════════╦═══════════╦═══════════════════════════╗
║ timestamp ║ device ║ accountid ║ last_48hour_device_count ║
╠═════════════════════╬══════════╬═══════════╬═══════════════════════════╣
║ 2018-10-29 18:52:30 ║ d1ed6e6 ║ DhHUXPw ║ 1 ║
║ 2018-11-01 18:52:30 ║ d123ff96 ║ zgffRDY ║ 1 ║
║ 2018-11-01 20:53:30 ║ e322ff96 ║ zgffRDY ║ 2 ║
║ 2018-11-02 21:33:30 ║ g133gf42 ║ zgffRDY ║ 3 ║
║ 2018-11-15 18:52:30 ║ d123ff96 ║ awfdsct ║ 1 ║
║ 2018-11-16 08:25:30 ║ d123ff96 ║ awfdsct ║ 1 ║
╚═════════════════════╩══════════╩═══════════╩═══════════════════════════╝
My current code looks like this.
count_list = []
for idx, row in df.iterrows():
account = row['accountid']
earliest = row['timestamp'] - pd.to_timedelta('48 hours')
current_time = row['timestamp']
filtered_data = df.query('timestamp >= @earliest and '
'timestamp < @current_time and '
'accountid == @account')
device_cnt = len(set(filtered_data['device']))
count_list.append(device_cnt)
df['last_48hour_device_count'] = count_list
I get the correct output, but my code runs way too slow, and I have a dataset with lots of observations in it.
Do you know of a better way to solve this?