Is it safe to pg_dump and pg_restore a new postgres database that has malware?
Probably.  But if you just recreate the same vulnerable setup, you will just get infected again from scratch.  They probably got in by guessing the weak password on a super-user account.  So set up all new passwords on the new system and make then strong ones. (pg_dump will not carry over your old passwords anyway, but pg_dumpall will.). It would also be good to lock down your new pg_hba.conf so that superusers can only connect locally, or at least only from white-listed IP addresses.
They probably created a new function which gives them shell access, and pg_dump will carry over that function definition.  But if they can't log in in the first place they can't use it anymore; and it probably relies on a dropped binary .so file, which pg_dump will not carry over.