cswork / libraryOpen practice workspace

Coding questions · PayPal

Clean and Analyze User Transactions with Python Functions

This question evaluates proficiency in data manipulation and feature engineering with Python and pandas, specifically cleaning transactional logs and deriving user-level time-based metrics such as inter-event intervals.

transactions

+---------+---------------------+---------+
| user_id | trans_ts            | amount  |
+---------+---------------------+---------+
| 11      |2024-06-03 10:00:00  | 25.80   |
| 11      |2024-06-03 10:05:00  | 10.50   |
| 12      |2024-06-03 12:00:00  | 40.00   |
| 11      |2024-06-04 09:00:00  | 15.00   |
| 12      |2024-06-05 13:20:00  | 33.30   |
+---------+---------------------+---------+
Scenario

Analyst must clean monthly transaction logs and derive user-level features for downstream modeling.

Question

Implement a Python function that removes users with fewer than 100 transactions per calendar month.

Implement another function that returns each user's average time between consecutive transactions in seconds.

Hints

Use pandas groupby with size()/filter and shift() on sorted timestamps; convert Timedelta to .dt.total_seconds().

Filter user-months by volume

Return all transactions that occur in user-months where the user has at least 100 transactions in that calendar month.

Table transactions

columntypeconstraints
user_idINTEGER
trans_tsTIMESTAMP
amountDECIMAL(10,2)

Sample data:

amounttrans_tsuser_id
25.82024-06-03 10:00:0011
10.52024-06-03 10:05:0011
402024-06-03 12:00:0012
152024-06-04 09:00:0011
33.32024-06-05 13:20:0012

Expected output

All transactions from user-months that have at least 100 transactions. With the sample data, no user-month reaches 100 transactions, so the result is empty.

Hints

  1. COUNT per user and calendar month using date_trunc('month', trans_ts).
  2. Join the monthly counts back to the base table and filter by count >= 100.

Average inter-transaction seconds

Compute each user's average time between consecutive transactions in seconds.

Table transactions

columntypeconstraints
user_idINTEGER
trans_tsTIMESTAMP
amountDECIMAL(10,2)

Sample data:

amounttrans_tsuser_id
25.82024-06-03 10:00:0011
10.52024-06-03 10:05:0011
402024-06-03 12:00:0012
152024-06-04 09:00:0011
33.32024-06-05 13:20:0012

Expected output

Per-user average seconds between consecutive transactions. For the sample data, user 11 has two gaps (300s and 82500s) averaging 41400.0; user 12 has one gap of 177600.0 seconds.

avg_inter_txn_secondsuser_id
4140011
17760012

Hints

  1. Use LAG to get the previous timestamp per user.
  2. Convert intervals to seconds with EXTRACT(EPOCH FROM ...), then average.