1

I looking for the amount of user in date range(-7) from pandas dataframe

Example.

UserID Date (Y/M/D)
100 2021/02/15
100 2021/02/10
100 2021/02/8
101 2021/02/10
102 2021/02/15
103 2021/02/10

What should I start I want receive result like it

UserID Date (Y/M/D) Count
100 2021/02/15 3 ## Because date (15 - 7) is 8 in dataframe it have 3 row in range 15 - 8
100 2021/02/10 2 ## Because date (10 - 7) is 3 in dataframe it have 2 row in range 10 - 3
100 2021/02/8 1
101 2021/02/10 1
102 2021/02/15 1
103 2021/02/10 1

2 Answers 2

0

Use custom lambda function:

#convert to datetimes
df['Date (Y/M/D)'] = pd.to_datetime(df['Date (Y/M/D)'])

#7 days timedelta
t = pd.Timedelta(7, unit='d')

#for each group counts values between previous 7 days and original
f = lambda x: x.apply(lambda y: (x.between(y - t, y).sum()))
df['new'] = df.groupby('UserID')['Date (Y/M/D)'].apply(f)
print (df)
   UserID Date (Y/M/D)  new
0     100   2021-02-15    3
1     100   2021-02-10    2
2     100   2021-02-08    1
3     101   2021-02-10    1
4     102   2021-02-15    1
5     103   2021-02-10    1
0
0

First convert your Date column from string to datetime (if you didn't do it before):

df['Date (Y/M/D)'] = pd.to_datetime(df['Date (Y/M/D)'])

Then take only rows from last 7 days:

df[df['Date (Y/M/D)'] >= pd.Timestamp.today().normalize() - pd.offsets.Day(7)]

And to generate Count column, run:

df['Count'] = df.groupby('UserID', group_keys=False).apply(
    lambda x: pd.Series(len(x) - np.arange(len(x)), x.index))

The result is:

   UserID Date (Y/M/D)  Count
0     100   2021-02-15      3
1     100   2021-02-10      2
2     100   2021-02-08      1
3     101   2021-02-10      1
4     102   2021-02-15      1
5     103   2021-02-10      1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.