Have there ever been any selective prosecution defences that have been successful ? A lot of news outlets claim that various racial groups are disproportionately targeted by prosecutors while framing charges. But has this as a legal defence ever succeeded and do courts take statistics into account ?
Yes. The earliest case in the U.S. serves as the basis of the SCOTUS case of Yick Yo v. Hopkins (1886) which struck down a San Francisco law that targeted Laundry services run by Chinese Immigrants. The case was later cited in 150 SCOTUS decisions and was used as a basis to reverse the Plessy v. Ferguson (1896) decision that permitted Jim Crow Laws in the Deep South.
That said, an affirmative defense of selective prosecution is hard to win, as selective enforcement has non-biased reasons to exist. For example, it is impossible for cops to ticket all speeders, so most departments may prioritize ticketing speeders who are egregious or overly reckless over speeders who are 5-10 miles over the limit but are keeping with the flow of the rest of traffic. The defense must show that the enforcement has a pattern of bias against a constitutionally protected class. If a cop writes 5 tickets in a day, of which only 1 ticket is for a woman, it does not inheritably mean that the cop is targeting men (but rather that men were 4 times as likely to be aggressive drivers), and it would have to be shown that there was a conscious choice by the officer (either personal or institutional) to pull over men violating the law and ignore women.