The ruling by U.S. District Court Judge Brian Buescher upholds an arbitration board's decision that Matthew Lebsack should be rehired following the 2016 incident, the Lincoln Journal Star reported.
The Omaha-based railroad giant did not indicate whether it would appeal the ruling.
"Union Pacific is reviewing the court’s decision and in the process of determining our next steps," the company said in a statement. "The behavior in question does not align with our values and should not be tolerated."
Lebsack admitted to defecating on a portion of the train connecting a locomotive and boxcar during a Nov. 20, 2016 stop. He also admitted to throwing soiled tissues out a window and raising his middle finger at a security camera abord the train.
The lawsuit also said he told his manager he left a "present" for his co-workers. The lawsuit didn't specify where the incident occurred.
Lebsack later blamed the incident on physical and mental issues. The company terminated him, citing a rule prohibiting conduct that is "negligent, insubordinate, dishonest, immoral, quarrelsome or discourteous."
In December, the arbitration board ruled the termination was excessive and said the railroad giant should require Lebsack to undergo a medical and psychological evaluation with the option to discipline him if he's found to not be fit for duty, according to the newspaper.
Union Pacific filed a lawsuit defending its right to fire him.
Buescher actually disagreed with the board, according to the newspaper, but said he wasn't allowed to consider the merits of the decision.
He said Union Pacific failed to prove the arbitration decision was not within the board's discretion.