I can think of a number of reasons why a player would attack you like that, none of them assuming that they are bad.
If there are three players left, a strong player, you, and a weak player, the weak player may be convinced by himself or the strong player that he will lose no matter what happens and that getting second is better than getting third. So, he will attack you and leave the strong player alone hoping that the strong player will attack the bigger threat first, namely you, and leave him for last.
The way to stop this from happening is to make the weak player believe that it is possible for him to win the entire game if only he would attack the strong player.
Another reason is that a player may believe that you have broken an alliance with him in the past and that if they make one with you now you will backstab them. Therefore, they should attack you to teach you that if you threaten them this way they will try to weaken you as much a possible before they get kicked out of the game.
The way to stop this is to not break alliances without either totally destroying them or to not break any alliances without good cause.
A third reason I can see why this would happen is if the weaker play thinks that he could win the game if only he had a little more territory to do so. He has only two choices on where to get this territory the strongest player on the map or you. Of course, he would attack you. He thinks that you are the weaker player and less like to be able to strike back at him.
The way to stop this is to strike back at him with everything you have saying that if he attacks you, you will totally destroy him no matter what.
These are just a few of the best reasons why someone would attack you like that and how to counter them.