Harold Ramirez slugged a walk-off homer in the 12th inning as the Miami Marlins rallied to defeat the visiting Minnesota Twins 5-4 on Thursday afternoon.

It was the second walk-off hit of the homestand for Ramirez, who crushed a 2-2 fastball from Cody Stashak (0-1). The 406-foot shot to left field was Ramirez's seventh homer of the season.

The Marlins, who have the worst record in the National League, sent the game to extra innings by scoring three runs in the ninth, avoiding what would've been a three-game sweep.

Jeff Brigham (1-0) tossed two scoreless innings to earn the win.

Twins reliever Sam Dyson, acquired from the San Francisco Giants on Wednesday, faced four batters in the ninth and got no outs, allowing a Jon Berti RBI double and leaving with the bases loaded.

Closer Taylor Rogers, working his third straight game, allowed a two-run single by Neil Walker that tied the score at 4-4.

Twins starter Michael Pineda allowed one run in six solid innings, scattering seven hits, striking out three and leaving with a 4-1 lead.

Marlins rookie Jordan Yamamoto allowed four runs while striking out eight in six innings. He had a 1.24 ERA in his first five starts but has an 8.05 ERA in four subsequent outings.

Miami lost shortstop Miguel Rojas, who was removed from the game in the fourth inning due to a right-hip injury suffered while running the bases.

Minnesota needed just four pitches to get on the board as Max Kepler pulled a 1-2 fastball for a leadoff home run down the right-field line. It was his 30th of the season, 10 more than his previous best.

Miami tied it up in the second. Starlin Castro's chopper over the third-base bag became an infield single. Castro scored when Ramirez smashed a one-out triple off the wall in right-center, eluding the glove of center fielder Byron Buxton.

Minnesota took a 3-1 lead in the fourth. Miguel Sano doubled and Ehire Adrianza was hit by a pitch, setting up Buxton's two-out, two-run double that hit chalk down the left-field line.

The Twins added a run in the fifth. One-out singles by Luis Arraez and Jorge Polanco put runners on the corners. Eddie Rosario's sacrifice fly drove in Arraez.

Ramirez also hit the game-ending sacrifice fly in a 3-2 victory against the Arizona Diamondbacks last Friday.