Alexa V. answered 04/25/19
10+ Years Translating Japanese-English with JLPT N2 Certification
They differ in levels of formality, with なぜ being the most formal and なんで being the least. Generally speaking, this means you could use なんで among friends or close family, but certainly not teachers or your boss. どうして is somewhat middle ground and could more or less be used among equals, while なぜ is formal. These should match the level of formality of your sentence structure too (ex: If you're using keigo, don't used なんで or どうして).
If we're talking about formal writing, like a paper for a class or a work document, なぜ is a standard choice unless you have good reasons for another.