The Ecuadorian climber was the only rider from the breakaway who managed to stay ahead of Miguel Angel Lopez (Astana-Qazaqstan), who came second after finishing eight seconds behind Carapaz.
Saturday's stage win came two days after Carapaz attacked to win stage 12.
"We knew that today was a very important stage for us, that we could repeat what we did the other day," Carapaz said. "The truth is that it took a long time to get away, but in the end I was there at the right time.
"I was able to attack, I went alone and then my breakaway companions joined me. They came with me and then there was a pretty good collaboration.
"At the end, I knew the climb very well. So, I tried to set my own pace, without losing hope, because I knew it was very hard. It has been a great stage, quite important for my record and for me. Above all, it gives a lot of morale."
Jumbo-Visma rider Roglic came third with a gap of 48 seconds to Quick-Step Alpha Vinyl's Evenepoel on the line.
Evenepoel retains the red jersey, 1:49 ahead of Roglic and 2:43 clear of Enric Mas (Movistar) ahead of another big mountain stage in Andalusia on Sunday.