Primoz Roglic, the overall leader, had a drama-free day to finish safely and keep the yellow jersey he claimed last Sunday.
After two sharp climbs and several attacks in the last 10 kilometers (six miles), Andersen broke away with three kilometres (two miles) left to finish 15 seconds ahead of the chasing pack.
In a stellar Tour for Slovenia, Luka Mezgec took the sprint for second and Simon Consonni was third.
Peter Sagan finished only fourth on a stage he targeted to close the gap in the points classification to green jersey wearer Sam Bennett.
Roglic, the former ski jumper, remained 44 seconds ahead of his fellow Slovenian Tadej Pogacar, and 59 clear of Egan Bernal, the defending champion.