I have a small dataframe. An example is given below.
+-------+---------+---------+------+----------+
| code | surplus | deficit | gone | has come |
+-------+---------+---------+------+----------+
| 0100 | 1000 | 0 | | |
| 0103 | 0 | 100 | | |
| 0104 | 0 | 600 | | |
| 0190 | 0 | 0 | | |
| 0191 | 0 | 800 | | |
| 0192 | 500 | 0 | | |
| 0193 | 700 | 0 | | |
| 0194 | 0 | 300 | | |
| 0195 | 0 | 0 | | |
+-------+---------+---------+------+----------+
I need to distribute the data from the column surplus
so as to cover the data in the column deficit
. In the column gone
write down how much I took from the column surplus
, and in the column has come
write down how much I added to fill the deficit. From the column surplus
I take the data as the values decrease. And always start with the largest deficit.
In my example it will look like this:
To cover the biggest deficit (In the example this is 800
) i take part of value 1000
.
To cover the next deficit (In the example this is 600
) i take the remainder of the value 1000
and I take 400
from the value 700
.
To cover the deficit 300
i take the remainder of the value 700
.
And, finally, to cover the deficit 100
i take part of value 500
.
The result should be the next dataframe:
+------+---------+---------+------+----------+
| code | surplus | deficit | gone | has come |
+------+---------+---------+------+----------+
| 0100 | 1000 | 0 | 1000 | 0 |
| 0103 | 0 | 100 | 0 | 100 |
| 0104 | 0 | 600 | 0 | 600 |
| 0190 | 0 | 0 | 0 | 0 |
| 0191 | 0 | 800 | 0 | 800 |
| 0192 | 500 | 0 | 100 | 0 |
| 0193 | 700 | 0 | 700 | 0 |
| 0194 | 0 | 300 | 0 | 300 |
| 0195 | 0 | 0 | 0 | 0 |
+------+---------+---------+------+----------+
The values in the columns surplus
and deficit
can be different.
I can't come up an algorithm for this task. I would be grateful for any ideas.