'Pandas dataframe column creation based on conditions on another dafaframe

I have one dataframe named df1 with on coefficient for each PAT x Segment x trage combination

df1 :

      PAT Segment         trage          coeff        age_min  age_max
0     GP  Epargne Euro    0 - 30 ans     2.717233        0       29
1     PC  Epargne Euro    0 - 30 ans     0.679354        0       29
2     PP  Epargne Euro    0 - 30 ans     1.318397        0       29
3     GP  Epargne UC      0 - 30 ans     3.105108        0       29
4     PC  Epargne UC      0 - 30 ans     0.436759        0       29
5     PP  Epargne UC      0 - 30 ans     1.609294        0       29
6     GP  Epargne Euro   30 - 40 ans     2.170444       30       39
7     PC  Epargne Euro   30 - 40 ans     0.613198       30       39
8     PP  Epargne Euro   30 - 40 ans     1.465155       30       39
9     GP  Epargne UC     30 - 40 ans     2.408381       30       39
10    PC  Epargne UC     30 - 40 ans     0.515426       30       39
11    PP  Epargne UC     30 - 40 ans     1.694122       30       39

...

43    PC  Epargne Euro   80 ans et +     0.634272       81       300
44    PP  Epargne Euro   80 ans et +     0.713068       81       300
45    GP  Epargne UC     80 ans et +     3.536907       81       300
46    PC  Epargne UC     80 ans et +     1.250310       81       300
47    PP  Epargne UC     80 ans et +     1.116990       81       300

I would like to create df2 (should look like below) where cfga i (from 1 to 41) is for each row the coefficient of df1 that satisfy the following conditions : df1.Segment=df2.Segment and df1.PAT=df2.PAT and df2.age + i-1 >= df1.age_min and df2.age + i-1 <= age_max

So for instance on the first two rows :

Row 1 : cfga1=0.679354, cfga29=0.679354, cfga30=0.613198

Row 2 : cfga1=0.679354, cfga28=0.679354, cfga29=0.613198

Segment       age PAT  cfga1  cfga2   cfga3   ... cfga28  cfga29  cfga30  ...cfga41
Epargne Euro  0   PC   0,679                               0,679   0,613
Epargne Euro  1   PC   0,679                       0,679   0,613   0,613
Epargne Euro  2   PC              
Epargne Euro  3   PC              
Epargne Euro  4   PC              
….    ….  ….              
Epargne UC    116 GP              
Epargne UC    117 GP              
Epargne UC    118 GP              
Epargne UC    119 GP              
Epargne UC    120 GP  

If you have any idea, it would be very appreciated

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source