Drivers are assigned a number from the two that are assigned to the team they are with. First the current WDC gets the #1 and his team mate #2. This applies before the ranking. The rest corresponds to the place the team finished the previous season.
So, for instance, now Redbull was nr. 1 so get 1 & 2, Mclaren was 2nd so get 3 & 4, Ferrari was 3rd – 5 & 6 etc. etc.
The exeption is with the WDC leaves the sport in which case the best team uses 0 & 2. I’m not 100% sure this is official, but it is the solution Williams used twice in the early nineties after respectively Mansell and then Prost retired as WDC.
For a long time this was not the case. New teams were assigned new numbers or filled empty spots. Teams fighting for the championship traded numbers, for instance, if the team with #11 and #12 won, they would get #1 and #2 and the previous championship team would instead switch to #11 and #12.
Because often the same teams fought at the front, this resulted in numbers becoming traditional. These were mainly 1/2, 5/6, 11/12 and 27/28 (but it depends on the era).
Numbers 27/28 were special for Ferrari because these were the numbers they used the most often. In their long dry spell from ’79 to ’89 they were “stuck” with them. When Prost joined them from McLaren as ’89 WDC, Ferrari got 1/2 and McLaren instead drove as 27/28 (for a year, before getting #1 back).