{"record":{"id":"01071b5720b8e61a","repo":"pandas-dev/pandas","slug":"cannot-convert-to-dtype-dtype-numpy-array-with","errorCode":null,"errorMessage":"cannot convert to '{dtype}'-dtype NumPy array with missing values. Specify an appropriate 'na_value' for this dtype.","messagePattern":"cannot convert to '(.+?)'-dtype NumPy array with missing values\\. Specify an appropriate 'na_value' for this dtype\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/masked.py","lineNumber":709,"sourceCode":"        ValueError: cannot convert to bool numpy array in presence of missing values\n\n        Specify a valid `na_value` instead\n\n        >>> a.to_numpy(dtype=\"bool\", na_value=False)\n        array([ True, False, False])\n        \"\"\"\n        hasna = self._hasna\n        dtype, na_value = to_numpy_dtype_inference(self, dtype, na_value, hasna)\n        if dtype is None:\n            dtype = np.dtype(object)\n\n        if hasna:\n            if (\n                dtype != np.dtype(object)\n                and not is_string_dtype(dtype)\n                and na_value is libmissing.NA\n            ):\n                raise ValueError(\n                    f\"cannot convert to '{dtype}'-dtype NumPy array \"\n                    \"with missing values. Specify an appropriate 'na_value' \"\n                    \"for this dtype.\"\n                )\n            # don't pass copy to astype -> always need a copy since we are mutating\n            with warnings.catch_warnings():\n                warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n                data = self._data.astype(dtype)\n            data[self._mask] = na_value\n        else:\n            with warnings.catch_warnings():\n                warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n                data = self._data.astype(dtype, copy=copy)\n            if self._readonly and not copy and astype_is_view(self.dtype, dtype):\n                data = data.view()\n                data.flags.writeable = False\n        return data\n","sourceCodeStart":691,"sourceCodeEnd":727,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/masked.py#L691-L727","documentation":"Raised by BaseMaskedArray.to_numpy when the masked array contains missing values but the requested dtype is neither object nor string and no explicit na_value was given (defaults to pandas.NA). pandas cannot embed a pd.NA sentinel into a numeric/datetime numpy array, so it refuses rather than silently corrupting the result.","triggerScenarios":"Calling arr.to_numpy(dtype='int64'), arr.to_numpy(dtype='bool'), arr.to_numpy(dtype='datetime64[ns]') (or np.asarray(arr, dtype=...)) on a masked array where self._hasna is True, without passing a compatible na_value.","commonSituations":"Passing nullable ExtensionArray data into a numpy-only routine that demands a concrete numeric dtype; forgetting a column has NaNs; refactoring code that previously used float64 (which silently gets np.nan) to use integer dtypes.","solutions":["Pass an explicit na_value compatible with the target dtype: arr.to_numpy(dtype='int64', na_value=-1) or arr.to_numpy(dtype='bool', na_value=False).","Drop or fill missing values first: arr = arr[~arr.isna()] or use Series.fillna(...) before converting.","Omit the dtype to get an object array that preserves pd.NA: arr.to_numpy().","Cast to float64 if NaN semantics are acceptable: arr.to_numpy(dtype='float64', na_value=np.nan)."],"exampleFix":"// before\narr.to_numpy(dtype=\"int64\")  # raises if arr has NA\n\n// after\narr.to_numpy(dtype=\"int64\", na_value=-1)","handlingStrategy":"validation","validationCode":"def to_numpy_safe(arr, dtype=None):\n    if getattr(arr, \"_hasna\", False) and dtype is not None:\n        import numpy as np\n        if np.dtype(dtype).kind in \"iubM\":\n            # need an explicit na_value\n            raise ValueError(f\"pass na_value for dtype {dtype} with NAs present\")\n    return arr.to_numpy(dtype=dtype)","typeGuard":"def needs_na_value(arr, dtype) -> bool:\n    import numpy as np\n    return (getattr(arr, \"_hasna\", False)\n            and np.dtype(dtype).kind not in \"OUS\")","tryCatchPattern":"try:\n    out = arr.to_numpy(dtype=\"int64\")\nexcept ValueError:\n    out = arr.to_numpy(dtype=\"int64\", na_value=-1)","preventionTips":["Before to_numpy with a numeric dtype, check arr.isna().any() and supply na_value or dropna.","Prefer to_numpy(dtype=..., na_value=...) over np.asarray for nullable arrays.","Document the na_value contract when handing nullable arrays to numpy-only code."],"tags":["masked-array","to-numpy","missing-values","na-value"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}