The same thing happens in Ecuador. All bags used to go systematically through and X-Ray machine but it took long, so now we have a light that randomly switches between red and green to tell you if you need to take your luggage through the X-Ray machine. And, yes, I had to do it in Panama too, twice.
This is usually done as part of customs, so it is to check for certain types of illegal goods. There is no official list AFAIK of what they are looking for but I imagine alcoholic drink bottles, perfume bottles, food items, animals and drugs would be on that list.
In other countries such as Canada, you get randomly picked to go through a custom inspection but it is done by hand. Luggage is not X-Rayed and you can see that the cart that unloads baggages from the play goes straight to the luggage belt and people take it from there.
Most of countries have X-ray on custom.
Just few of the countries control them systematically (or just often, many people per flights).
It is not just for drugs or safety. Often is just to have a better custom control, to see if you are importing commercial stuffs, that requires taxes.
Credit:stackoverflow.com‘