def maybe_downcast_to_dtype(result, dtype):
if is_scalar(result):<EOL><INDENT>return result<EOL><DEDENT>def trans(x):<EOL><INDENT>return x<EOL><DEDENT>if isinstance(dtype, str):<EOL><INDENT>if dtype == '<STR_LIT>':<EOL><INDENT>inferred_type = lib.infer_dtype(ensure_object(result.ravel()),<EOL>skipna=False)<EOL>if inferred_type == '<STR_LIT>':<EOL><INDENT>dtype = '<STR_LIT:bool>'<EOL><DEDENT>elif inferred_type == '<STR_LIT>':<EOL><INDENT>dtype = '<STR_LIT>'<EOL><DEDENT>elif inferred_type == '<STR_LIT>':<EOL><INDENT>dtype = '<STR_LIT>'<EOL><DEDENT>elif inferred_type == '<STR_LIT>':<EOL><INDENT>dtype = '<STR_LIT>'<EOL><DEDENT>elif inferred_type == '<STR_LIT>':<EOL><INDENT>dtype = '<STR_LIT>'<EOL>if issubclass(result.dtype.type, np.number):<EOL><INDENT>def trans(x):  <EOL><INDENT>return x.round()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>dtype = '<STR_LIT:object>'<EOL><DEDENT><DEDENT><DEDENT>if isinstance(dtype, str):<EOL><INDENT>dtype = np.dtype(dtype)<EOL><DEDENT>try:<EOL><INDENT>if dtype.kind == result.dtype.kind:<EOL><INDENT>if (result.dtype.itemsize <= dtype.itemsize and<EOL>np.prod(result.shape)):<EOL><INDENT>return result<EOL><DEDENT><DEDENT>if is_bool_dtype(dtype) or is_integer_dtype(dtype):<EOL><INDENT>if not np.prod(result.shape):<EOL><INDENT>return trans(result).astype(dtype)<EOL><DEDENT>r = result.ravel()<EOL>arr = np.array([r[<NUM_LIT:0>]])<EOL>if (isna(arr).any() or<EOL>not np.allclose(arr, trans(arr).astype(dtype), rtol=<NUM_LIT:0>)):<EOL><INDENT>return result<EOL><DEDENT>elif not isinstance(r[<NUM_LIT:0>], (np.integer, np.floating, np.bool, int,<EOL>float, bool)):<EOL><INDENT>return result<EOL><DEDENT>if (issubclass(result.dtype.type, (np.object_, np.number)) and<EOL>notna(result).all()):<EOL><INDENT>new_result = trans(result).astype(dtype)<EOL>try:<EOL><INDENT>if np.allclose(new_result, result, rtol=<NUM_LIT:0>):<EOL><INDENT>return new_result<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>if (new_result == result).all():<EOL><INDENT>return new_result<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif (issubclass(dtype.type, np.floating) and<EOL>not is_bool_dtype(result.dtype)):<EOL><INDENT>return result.astype(dtype)<EOL><DEDENT>elif dtype.kind in ['<STR_LIT:M>', '<STR_LIT:m>'] and result.dtype.kind in ['<STR_LIT:i>', '<STR_LIT:f>']:<EOL><INDENT>try:<EOL><INDENT>result = result.astype(dtype)<EOL><DEDENT>except Exception:<EOL><INDENT>if dtype.tz:<EOL><INDENT>from pandas import to_datetime<EOL>result = to_datetime(result).tz_localize('<STR_LIT>')<EOL>result = result.tz_convert(dtype.tz)<EOL><DEDENT><DEDENT><DEDENT>elif dtype.type == Period:<EOL><INDENT>from pandas.core.arrays import PeriodArray<EOL>return PeriodArray(result, freq=dtype.freq)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return result<EOL>
try to cast to the specified dtype (e.g. convert back to bool/int
    or could be an astype of float64->float32