An animal's survival hinges on its ability to integrate past information to modify future behavior. The nematode C. elegans adapts its behavior based on prior experiences with pathogen exposure, transitioning from attraction to avoidance of the pathogen. A systematic screen for the neural circuits that integrate the information of previous pathogen exposure to modify behavior has not been feasible because of the lack of tools for neuron type specific perturbations. We overcame this challenge using methods based on compressed sensing to efficiently determine the roles of individual neuron types in learned avoidance behavior. Our screen revealed that distinct sets of neurons drive exit from lawns of pathogenic bacteria and prevent lawn re-entry. Using calcium imaging of freely behaving animals and optogenetic perturbations, we determined the neural dynamics that regulate one key behavioral transition after infection: stalled re-entry into bacterial lawns. We find that key neuron types govern pathogen lawn specific stalling but allow the animal to enter nonpathogenic E. coli lawns. Our study shows that learned pathogen avoidance requires coordinated transitions in discrete neural circuits and reveals the modular structure of this complex adaptive behavioral response to infection.