I have 2 dataframes:
df1:
| artist_id | concert_date | region_id |
|---|---|---|
| 12345 | 2019-10 | 22 |
| 33322 | 2018-11 | 44 |
df2:
| artist_id | date | region_id | popularity |
|---|---|---|---|
| 12345 | 2019-10 | 22 | 76 |
| 12345 | 2019-11 | 44 | 23 |
I need to add the median of the artist's popularity (which needs to be calculated only for the last 3 months before the concert and only for the same region) from the second table to the first.
That is, the first table should look like (figures are invented, the point is not in them now): df1:
| artist_id | concert_date | region_id | popularity_median_last3month |
|---|---|---|---|
| 12345 | 2019-10 | 22 | 55 |
| 33322 | 2018-11 | 44 | 44 |
Right now I'm using the following loop:
df1['popularity_median_last3month'] = pd.Series(dtype='int')
for i in range(len(df1)):
df1['popularity_median_last3month'].values[i] = df2[(df2.artist_id==df1.artist_id.values[i])&(df2.region_id==df1.region_id.values[i])&(df2.date<=df1.concert_date.values[i])][-3:].popularity.median()
however, it takes too long with a large amount of data.
Please tell me how to avoid the loop