I have a dataframe like this:
SEG | FAM | GAMA | MIN_RAT | MAX_RAT | VALOR |
---|---|---|---|---|---|
PE | 001 | 002 | 1 | 2 | 5,15 |
PE | 001 | 002 | 2,1 | 3 | 2,55 |
And I need to “expand” the df adding new rows to make a new dataframe like this:
SEG | FAM | GAMA | MIN_RAT | MAX_RAT | VALOR |
---|---|---|---|---|---|
PE | 001 | 002 | 1 | 1 | 10,30 |
PE | 001 | 002 | 1,1 | 1,1 | 9,79 |
PE | 001 | 002 | 1,2 | 1,2 | 9,27 |
PE | 001 | 002 | 1,3 | 1,3 | 8,76 |
PE | 001 | 002 | 1,4 | 1,4 | 8,24 |
PE | 001 | 002 | 1,5 | 1,5 | 7,73 |
PE | 001 | 002 | 1,6 | 1,6 | 7,21 |
PE | 001 | 002 | 1,7 | 1,7 | 6,70 |
PE | 001 | 002 | 1,8 | 1,8 | 6,18 |
PE | 001 | 002 | 1,9 | 1,9 | 5,67 |
PE | 001 | 002 | 2 | 2 | 5,15 |
PE | 001 | 002 | 2,1 | 2,1 | 5,10 |
PE | 001 | 002 | 2,2 | 2,2 | 4,82 |
PE | 001 | 002 | 2,3 | 2,3 | 4,53 |
PE | 001 | 002 | 2,4 | 2,4 | 4,25 |
PE | 001 | 002 | 2,5 | 2,5 | 3,97 |
PE | 001 | 002 | 2,6 | 2,6 | 3,68 |
PE | 001 | 002 | 2,7 | 2,7 | 3,40 |
PE | 001 | 002 | 2,8 | 2,8 | 3,12 |
PE | 001 | 002 | 2,9 | 2,9 | 2,83 |
PE | 001 | 002 | 3 | 3 | 2,55 |
The values of the column “VALOR” are constructed dividing :
5.15 of the original table by the number of new rows between MIN_RAT=1 and MAX_RAT = 2 and adding that value to 5.15 (in this case we add 0.515 in each row)
2,55 of the original table by the number of new rows between MIN_RAT=2,1 and MAX_RAT = 3 and adding that value to 2.55 (in this case we add 0.28 in each row)
Is it possible to do this optimally?
Advertisement
Answer
Let’s try this:
JavaScript
x
11
11
1
rnglist=[np.arange(i, j+.1, 0.1) for i, j in list(zip(df['MIN_RAT'], df['MAX_RAT']))]
2
3
dfm = df.reindex(df.index.repeat([len(x) for x in rnglist]))
4
5
dfm['MIN_RAT'] = np.concatenate(rnglist)
6
dfm['MAX_RAT'] = np.concatenate(rnglist)
7
8
dfm['VALOR']= dfm.groupby(level=0)['VALOR']
9
.transform(lambda x: ((x.notna().cumsum()-1)/(x.count()-1)*x.iloc[0])[::-1]+x.iloc[0])
10
print(dfm)
11
Output:
JavaScript
1
23
23
1
EG FAM GAMA MIN_RAT MAX_RAT VALOR
2
0 PE 1 2 1.0 1.0 10.300000
3
0 PE 1 2 1.1 1.1 9.785000
4
0 PE 1 2 1.2 1.2 9.270000
5
0 PE 1 2 1.3 1.3 8.755000
6
0 PE 1 2 1.4 1.4 8.240000
7
0 PE 1 2 1.5 1.5 7.725000
8
0 PE 1 2 1.6 1.6 7.210000
9
0 PE 1 2 1.7 1.7 6.695000
10
0 PE 1 2 1.8 1.8 6.180000
11
0 PE 1 2 1.9 1.9 5.665000
12
0 PE 1 2 2.0 2.0 5.150000
13
1 PE 1 2 2.1 2.1 5.100000
14
1 PE 1 2 2.2 2.2 4.816667
15
1 PE 1 2 2.3 2.3 4.533333
16
1 PE 1 2 2.4 2.4 4.250000
17
1 PE 1 2 2.5 2.5 3.966667
18
1 PE 1 2 2.6 2.6 3.683333
19
1 PE 1 2 2.7 2.7 3.400000
20
1 PE 1 2 2.8 2.8 3.116667
21
1 PE 1 2 2.9 2.9 2.833333
22
1 PE 1 2 3.0 3.0 2.550000
23