def mod(x, modulus):
    numer, denom = x.as_numer_denom()
return numer * mod_inverse(denom, modulus) % modulus
pprint(B_rref[0].applyfunc(lambda x: mod(x, 5)))
Sympy: Solving Matrices in a finite field