Home > Blockchain >  Using pandas, how can I find out if my customer made a purchase last month or two months ago?
Using pandas, how can I find out if my customer made a purchase last month or two months ago?

Time:12-28

I'm new to python and new to pandas. Of course, if my project used exact dates, I could easily do this, but unfortunately, the date type is a little different, and as you can see, the sign 08 is after the year 1401, which means it is the eighth month of the year 1401.

enter image description here

I currently know that these 3 customers have bought from me this month. But I want to know if these 3 customers bought from me in the previous month or two months ago? If they do, I will give them a discount. Of course, I should also say that the number 08 is not always fixed, but it could be 09 in the next month. I just want to know if they bought from me 1 month ago or not?

According to the picture, now only Sara should get a discount

CodePudding user response:

You could convert the purchase date to an integer and calculate the number of months from there.

For instance, you have the purchase month 1901/07 and you want to know in 1901/08 how many months the last purchase took place. So you convert both values to integers and subtract them (190108 - 190107 = 1).

import pandas as pd
df = pd.DataFrame({'customer': ['david', 'sara'], 'date': ['1901/03', '1901/07']})

# Manually setting the reference month (190108 for Year 1901 and Month 08)
df['months'] = 190108 - df['date'].replace('/', '', regex=True).astype(int)

# Check if eligible for discount
df['discount'] = df['months'].isin([1, 2])
customer date months discount
0 david 1901/03 5 False
1 sara 1901/07 1 True

To compare with today's month you could to the following:

df['months'] = int(pd.Timestamp.now().strftime('%Y%m'))\
                - df['date'].replace('/', '', regex=True).astype(int)
  • Related