Can this function not be replace by a single numpy expression?