Avoiding for loops is using pandas

Consider the following example of an e-commerce data:

Cust ID Order ID Item category Amount Order Date
A xyz Electronics 30 20220726
B abc Home appliance 40 20220725

A ML problem statement requires, to identify “UserChurn” prediction. The business team feels has proposed following features:

  1. The last order category placed
  2. The number of orders placed in the last week
  3. The amount spent in the last week

Note here that, it’s logically quite convenient to start with:

for i in df[‘Cust ID’].unique:

However, the performance of such a code will be sub-optimal. Each of the above three features can be calculated by a combination of group by and aggregation. If not, in one line, as separate lines, grouped by Cust ID, as separate tables, which then can be merged. This will still be faster than a for loop.

Would any learner like to volunteer to submit the answer?