Consider using np.clip for the clipping part.