Three pixels are always dark
mean, std = D.mean(axis=0), D.std(axis=0)
print((std == 0).sum()) # 3
Three pixels are always dark in all 1,797 digit images. They sit in corners where nobody writes. Their standard deviation is exactly zero, so (D - mean) / std divides by zero and produces NaN.
The fix keeps the finding visible rather than hiding it:
Z = (D - mean) / np.where(std == 0, 1.0, std)