def astype(self, dtype, copy=True): dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, self.dtype): if copy: return self.copy() return self elif isinstance(dtype, _IntegerDtype): arr = self._ndarray.copy() mask = self.isna() arr[mask] = 0 values = arr.astype(dtype.numpy_dtype) return IntegerArray(values, mask, copy=False) elif isinstance(dtype, FloatingDtype): arr = self.copy() mask = self.isna() arr[mask] = "0" values = arr.astype(dtype.numpy_dtype) return FloatingArray(values, mask, copy=False) elif np.issubdtype(dtype, np.floating): arr = self._ndarray.copy() mask = self.isna() arr[mask] = 0 values = arr.astype(dtype) values[mask] = np.nan return values return super().astype(dtype, copy)
def _maybe_mask_result(self, result, mask, other, op_name: str): """ Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str """ # if we have a float operand we are by-definition # a float result # or our op is a divide if (is_float_dtype(other) or is_float(other)) or ( op_name in ["rtruediv", "truediv"] ): from pandas.core.arrays import FloatingArray return FloatingArray(result, mask, copy=False) if result.dtype == "timedelta64[ns]": from pandas.core.arrays import TimedeltaArray result[mask] = iNaT return TimedeltaArray._simple_new(result) return type(self)(result, mask, copy=False)
def reconstruct(x): # we don't worry about scalar `x` here, since we # raise for reduce up above. from pandas.core.arrays import ( BooleanArray, FloatingArray, IntegerArray, ) if is_bool_dtype(x.dtype): m = mask.copy() return BooleanArray(x, m) elif is_integer_dtype(x.dtype): m = mask.copy() return IntegerArray(x, m) elif is_float_dtype(x.dtype): m = mask.copy() if x.dtype == np.float16: # reached in e.g. np.sqrt on BooleanArray # we don't support float16 x = x.astype(np.float32) return FloatingArray(x, m) else: x[mask] = np.nan return x
def astype(self, dtype, copy=True): dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, self.dtype): if copy: return self.copy() return self elif isinstance(dtype, _IntegerDtype): arr = self._ndarray.copy() mask = self.isna() arr[mask] = 0 values = arr.astype(dtype.numpy_dtype) return IntegerArray(values, mask, copy=False) elif isinstance(dtype, FloatingDtype): # error: Incompatible types in assignment (expression has type # "StringArray", variable has type "ndarray") arr = self.copy() # type: ignore[assignment] mask = self.isna() arr[mask] = "0" values = arr.astype(dtype.numpy_dtype) return FloatingArray(values, mask, copy=False) elif np.issubdtype(dtype, np.floating): arr = self._ndarray.copy() mask = self.isna() arr[mask] = 0 values = arr.astype(dtype) values[mask] = np.nan return values return super().astype(dtype, copy)
def _maybe_mask_result(self, result, mask, other, op_name: str): """ Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str """ # if we have a float operand we are by-definition # a float result # or our op is a divide if (is_float_dtype(other) or is_float(other)) or (op_name in ["rtruediv", "truediv"]): from pandas.core.arrays import FloatingArray return FloatingArray(result, mask, copy=False) elif is_bool_dtype(result): return BooleanArray(result, mask, copy=False) elif is_integer_dtype(result): from pandas.core.arrays import IntegerArray return IntegerArray(result, mask, copy=False) else: result[mask] = np.nan return result
def test_floating_array_disallows_float16(): # GH#44715 arr = np.array([1, 2], dtype=np.float16) mask = np.array([False, False]) msg = "FloatingArray does not support np.float16 dtype" with pytest.raises(TypeError, match=msg): FloatingArray(arr, mask)
def test_construct_from_float_strings(values): # see also test_to_integer_array_str expected = pd.array([float(values[0]), 2, None], dtype="Float64") res = pd.array(values, dtype="Float64") tm.assert_extension_array_equal(res, expected) res = FloatingArray._from_sequence(values) tm.assert_extension_array_equal(res, expected)
def test_pow_scalar(): a = pd.array([-1, 0, 1, None, 2], dtype="Int64") result = a**0 expected = pd.array([1, 1, 1, 1, 1], dtype="Int64") tm.assert_extension_array_equal(result, expected) result = a**1 expected = pd.array([-1, 0, 1, None, 2], dtype="Int64") tm.assert_extension_array_equal(result, expected) result = a**pd.NA expected = pd.array([None, None, 1, None, None], dtype="Int64") tm.assert_extension_array_equal(result, expected) result = a**np.nan expected = FloatingArray( np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64"), np.array([False, False, False, True, False]), ) tm.assert_extension_array_equal(result, expected) # reversed a = a[1:] # Can't raise integers to negative powers. result = 0**a expected = pd.array([1, 0, None, 0], dtype="Int64") tm.assert_extension_array_equal(result, expected) result = 1**a expected = pd.array([1, 1, 1, 1], dtype="Int64") tm.assert_extension_array_equal(result, expected) result = pd.NA**a expected = pd.array([1, None, None, None], dtype="Int64") tm.assert_extension_array_equal(result, expected) result = np.nan**a expected = FloatingArray( np.array([1, np.nan, np.nan, np.nan], dtype="float64"), np.array([False, False, True, False]), ) tm.assert_extension_array_equal(result, expected)
def test_pow_scalar(dtype): a = pd.array([-1, 0, 1, None, 2], dtype=dtype) result = a**0 expected = pd.array([1, 1, 1, 1, 1], dtype=dtype) tm.assert_extension_array_equal(result, expected) result = a**1 expected = pd.array([-1, 0, 1, None, 2], dtype=dtype) tm.assert_extension_array_equal(result, expected) result = a**pd.NA expected = pd.array([None, None, 1, None, None], dtype=dtype) tm.assert_extension_array_equal(result, expected) result = a**np.nan # TODO np.nan should be converted to pd.NA / missing before operation? expected = FloatingArray( np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask, ) tm.assert_extension_array_equal(result, expected) # reversed a = a[1:] # Can't raise integers to negative powers. result = 0**a expected = pd.array([1, 0, None, 0], dtype=dtype) tm.assert_extension_array_equal(result, expected) result = 1**a expected = pd.array([1, 1, 1, 1], dtype=dtype) tm.assert_extension_array_equal(result, expected) result = pd.NA**a expected = pd.array([1, None, None, None], dtype=dtype) tm.assert_extension_array_equal(result, expected) result = np.nan**a expected = FloatingArray(np.array([1, np.nan, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask) tm.assert_extension_array_equal(result, expected)
def test_divide_by_zero(zero, negative): # https://github.com/pandas-dev/pandas/issues/27398 a = pd.array([0, 1, -1, None], dtype="Int64") result = a / zero expected = FloatingArray( np.array([np.nan, np.inf, -np.inf, 1], dtype="float64"), np.array([False, False, False, True]), ) if negative: expected *= -1 tm.assert_extension_array_equal(result, expected)
def test_ufuncs_single_float(ufunc): a = pd.array([1, 2, -3, np.nan]) with np.errstate(invalid="ignore"): result = ufunc(a) expected = FloatingArray(ufunc(a.astype(float)), mask=a._mask) tm.assert_extension_array_equal(result, expected) s = pd.Series(a) with np.errstate(invalid="ignore"): result = ufunc(s) expected = pd.Series(expected) tm.assert_series_equal(result, expected)
def test_divide_by_zero(dtype, zero, negative): # TODO pending NA/NaN discussion # https://github.com/pandas-dev/pandas/issues/32265/ a = pd.array([0, 1, -1, None], dtype=dtype) result = a / zero expected = FloatingArray( np.array([np.nan, np.inf, -np.inf, np.nan], dtype=dtype.numpy_dtype), np.array([False, False, False, True]), ) if negative: expected *= -1 tm.assert_extension_array_equal(result, expected)
def test_floating_array_constructor(): values = np.array([1, 2, 3, 4], dtype="float64") mask = np.array([False, False, False, True], dtype="bool") result = FloatingArray(values, mask) expected = pd.array([1, 2, 3, np.nan], dtype="Float64") tm.assert_extension_array_equal(result, expected) tm.assert_numpy_array_equal(result._data, values) tm.assert_numpy_array_equal(result._mask, mask) msg = r".* should be .* numpy array. Use the 'pd.array' function instead" with pytest.raises(TypeError, match=msg): FloatingArray(values.tolist(), mask) with pytest.raises(TypeError, match=msg): FloatingArray(values, mask.tolist()) with pytest.raises(TypeError, match=msg): FloatingArray(values.astype(int), mask) msg = r"__init__\(\) missing 1 required positional argument: 'mask'" with pytest.raises(TypeError, match=msg): FloatingArray(values)
def _maybe_mask_result(self, result, mask, other, op_name: str): """ Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str """ if op_name == "divmod": # divmod returns a tuple div, mod = result return ( self._maybe_mask_result(div, mask, other, "floordiv"), self._maybe_mask_result(mod, mask, other, "mod"), ) # if we have a float operand we are by-definition # a float result # or our op is a divide if ((is_float_dtype(other) or is_float(other)) or (op_name in ["rtruediv", "truediv"]) or (is_float_dtype(self.dtype) and is_numeric_dtype(result.dtype))): from pandas.core.arrays import FloatingArray return FloatingArray(result, mask, copy=False) elif is_bool_dtype(result): from pandas.core.arrays import BooleanArray return BooleanArray(result, mask, copy=False) elif result.dtype == "timedelta64[ns]": # e.g. test_numeric_arr_mul_tdscalar_numexpr_path from pandas.core.arrays import TimedeltaArray if not isinstance(result, TimedeltaArray): result = TimedeltaArray._simple_new(result) result[mask] = result.dtype.type("NaT") return result elif is_integer_dtype(result): from pandas.core.arrays import IntegerArray return IntegerArray(result, mask, copy=False) else: result[mask] = np.nan return result
def reconstruct(x): # we don't worry about scalar `x` here, since we # raise for reduce up above. if is_integer_dtype(x.dtype): from pandas.core.arrays import IntegerArray m = mask.copy() return IntegerArray(x, m) elif is_float_dtype(x.dtype): from pandas.core.arrays import FloatingArray m = mask.copy() return FloatingArray(x, m) else: x[mask] = np.nan return x
def _maybe_mask_result(self, result, mask): """ Parameters ---------- result : array-like or tuple[array-like] mask : array-like bool """ if isinstance(result, tuple): # i.e. divmod div, mod = result return ( self._maybe_mask_result(div, mask), self._maybe_mask_result(mod, mask), ) if is_float_dtype(result.dtype): from pandas.core.arrays import FloatingArray return FloatingArray(result, mask, copy=False) elif is_bool_dtype(result.dtype): from pandas.core.arrays import BooleanArray return BooleanArray(result, mask, copy=False) elif result.dtype == "timedelta64[ns]": # e.g. test_numeric_arr_mul_tdscalar_numexpr_path from pandas.core.arrays import TimedeltaArray if not isinstance(result, TimedeltaArray): result = TimedeltaArray._simple_new(result) result[mask] = result.dtype.type("NaT") return result elif is_integer_dtype(result.dtype): from pandas.core.arrays import IntegerArray return IntegerArray(result, mask, copy=False) else: result[mask] = np.nan return result
def test_floating_array_disallows_float16(request): # GH#44715 arr = np.array([1, 2], dtype=np.float16) mask = np.array([False, False]) msg = "FloatingArray does not support np.float16 dtype" with pytest.raises(TypeError, match=msg): FloatingArray(arr, mask) if np_version_under1p19 or (locale.getlocale()[0] != "en_US" and not is_platform_windows()): # the locale condition may need to be refined; this fails on # the CI in the ZH_CN build mark = pytest.mark.xfail( reason="numpy does not raise on np.dtype('Float16')") request.node.add_marker(mark) with pytest.raises(TypeError, match="data type 'Float16' not understood"): pd.array([1.0, 2.0], dtype="Float16")
def test_to_numpy_na_value_with_nan(): # array with both NaN and NA -> only fill NA with `na_value` arr = FloatingArray(np.array([0.0, np.nan, 0.0]), np.array([False, False, True])) result = arr.to_numpy(dtype="float64", na_value=-1) expected = np.array([0.0, np.nan, -1.0], dtype="float64") tm.assert_numpy_array_equal(result, expected)
def array( data: Sequence[object] | AnyArrayLike, dtype: Dtype | None = None, copy: bool = True, ) -> ExtensionArray: """ Create an array. .. versionadded:: 0.24.0 Parameters ---------- data : Sequence of objects The scalars inside `data` should be instances of the scalar type for `dtype`. It's expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`. dtype : str, np.dtype, or ExtensionDtype, optional The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas using :meth:`pandas.api.extensions.register_extension_dtype`. If not specified, there are two possibilities: 1. When `data` is a :class:`Series`, :class:`Index`, or :class:`ExtensionArray`, the `dtype` will be taken from the data. 2. Otherwise, pandas will attempt to infer the `dtype` from the data. Note that when `data` is a NumPy array, ``data.dtype`` is *not* used for inferring the array type. This is because NumPy cannot represent all the types of data that can be held in extension arrays. Currently, pandas will infer an extension dtype for sequences of ============================== ===================================== Scalar Type Array Type ============================== ===================================== :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray` :class:`pandas.Period` :class:`pandas.arrays.PeriodArray` :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray` :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray` :class:`int` :class:`pandas.arrays.IntegerArray` :class:`float` :class:`pandas.arrays.FloatingArray` :class:`str` :class:`pandas.arrays.StringArray` :class:`bool` :class:`pandas.arrays.BooleanArray` ============================== ===================================== For all other cases, NumPy's usual inference rules will be used. .. versionchanged:: 1.0.0 Pandas infers nullable-integer dtype for integer data, string dtype for string data, and nullable-boolean dtype for boolean data. .. versionchanged:: 1.2.0 Pandas now also infers nullable-floating dtype for float-like input data copy : bool, default True Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if ``copy=False``. Returns ------- ExtensionArray The newly created array. Raises ------ ValueError When `data` is not 1-dimensional. See Also -------- numpy.array : Construct a NumPy array. Series : Construct a pandas Series. Index : Construct a pandas Index. arrays.PandasArray : ExtensionArray wrapping a NumPy array. Series.array : Extract the array stored within a Series. Notes ----- Omitting the `dtype` argument means pandas will attempt to infer the best array type from the values in the data. As new array types are added by pandas and 3rd party libraries, the "best" array type may change. We recommend specifying `dtype` to ensure that 1. the correct array type for the data is returned 2. the returned array type doesn't change as new extension types are added by pandas and third-party libraries Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the `dtype` as a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data. In this event, the following would no longer return a :class:`arrays.PandasArray` backed by a NumPy array. >>> pd.array(['a', 'b'], dtype=str) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 This would instead return the new ExtensionArray dedicated for string data. If you really need the new array to be backed by a NumPy array, specify that in the dtype. >>> pd.array(['a', 'b'], dtype=np.dtype("<U1")) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 Finally, Pandas has arrays that mostly overlap with NumPy * :class:`arrays.DatetimeArray` * :class:`arrays.TimedeltaArray` When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray`` rather than a ``PandasArray``. This is for symmetry with the case of timezone-aware data, which NumPy does not natively support. >>> pd.array(['2015', '2016'], dtype='datetime64[ns]') <DatetimeArray> ['2015-01-01 00:00:00', '2016-01-01 00:00:00'] Length: 2, dtype: datetime64[ns] >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]') <TimedeltaArray> ['0 days 01:00:00', '0 days 02:00:00'] Length: 2, dtype: timedelta64[ns] Examples -------- If a dtype is not specified, pandas will infer the best dtype from the values. See the description of `dtype` for the types pandas infers for. >>> pd.array([1, 2]) <IntegerArray> [1, 2] Length: 2, dtype: Int64 >>> pd.array([1, 2, np.nan]) <IntegerArray> [1, 2, <NA>] Length: 3, dtype: Int64 >>> pd.array([1.1, 2.2]) <FloatingArray> [1.1, 2.2] Length: 2, dtype: Float64 >>> pd.array(["a", None, "c"]) <StringArray> ['a', <NA>, 'c'] Length: 3, dtype: string >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] Length: 2, dtype: period[D] You can use the string alias for `dtype` >>> pd.array(['a', 'b', 'a'], dtype='category') ['a', 'b', 'a'] Categories (2, object): ['a', 'b'] Or specify the actual dtype >>> pd.array(['a', 'b', 'a'], ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)) ['a', 'b', 'a'] Categories (3, object): ['a' < 'b' < 'c'] If pandas does not infer a dedicated extension type a :class:`arrays.PandasArray` is returned. >>> pd.array([1 + 1j, 3 + 2j]) <PandasArray> [(1+1j), (3+2j)] Length: 2, dtype: complex128 As mentioned in the "Notes" section, new extension types may be added in the future (by pandas or 3rd party libraries), causing the return value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype` as a NumPy dtype if you need to ensure there's no future change in behavior. >>> pd.array([1, 2], dtype=np.dtype("int32")) <PandasArray> [1, 2] Length: 2, dtype: int32 `data` must be 1-dimensional. A ValueError is raised when the input has the wrong dimensionality. >>> pd.array(1) Traceback (most recent call last): ... ValueError: Cannot pass scalar '1' to 'pandas.array'. """ from pandas.core.arrays import ( BooleanArray, DatetimeArray, FloatingArray, IntegerArray, IntervalArray, PandasArray, StringArray, TimedeltaArray, period_array, ) if lib.is_scalar(data): msg = f"Cannot pass scalar '{data}' to 'pandas.array'." raise ValueError(msg) if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ABCExtensionArray)): # Note: we exclude np.ndarray here, will do type inference on it dtype = data.dtype data = extract_array(data, extract_numpy=True) # this returns None for not-found dtypes. if isinstance(dtype, str): dtype = registry.find(dtype) or dtype if is_extension_array_dtype(dtype): cls = cast(ExtensionDtype, dtype).construct_array_type() return cls._from_sequence(data, dtype=dtype, copy=copy) if dtype is None: inferred_dtype = lib.infer_dtype(data, skipna=True) if inferred_dtype == "period": try: return period_array(data, copy=copy) except IncompatibleFrequency: # We may have a mixture of frequencies. # We choose to return an ndarray, rather than raising. pass elif inferred_dtype == "interval": try: return IntervalArray(data, copy=copy) except ValueError: # We may have a mixture of `closed` here. # We choose to return an ndarray, rather than raising. pass elif inferred_dtype.startswith("datetime"): # datetime, datetime64 try: return DatetimeArray._from_sequence(data, copy=copy) except ValueError: # Mixture of timezones, fall back to PandasArray pass elif inferred_dtype.startswith("timedelta"): # timedelta, timedelta64 return TimedeltaArray._from_sequence(data, copy=copy) elif inferred_dtype == "string": return StringArray._from_sequence(data, copy=copy) elif inferred_dtype == "integer": return IntegerArray._from_sequence(data, copy=copy) elif inferred_dtype in ("floating", "mixed-integer-float"): return FloatingArray._from_sequence(data, copy=copy) elif inferred_dtype == "boolean": return BooleanArray._from_sequence(data, copy=copy) # Pandas overrides NumPy for # 1. datetime64[ns] # 2. timedelta64[ns] # so that a DatetimeArray is returned. if is_datetime64_ns_dtype(dtype): return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy) elif is_timedelta64_ns_dtype(dtype): return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy) return PandasArray._from_sequence(data, dtype=dtype, copy=copy)
def test_equals_nan_vs_na(): # GH#44382 mask = np.zeros(3, dtype=bool) data = np.array([1.0, np.nan, 3.0], dtype=np.float64) left = FloatingArray(data, mask) assert left.equals(left) tm.assert_extension_array_equal(left, left) assert left.equals(left.copy()) assert left.equals(FloatingArray(data.copy(), mask.copy())) mask2 = np.array([False, True, False], dtype=bool) data2 = np.array([1.0, 2.0, 3.0], dtype=np.float64) right = FloatingArray(data2, mask2) assert right.equals(right) tm.assert_extension_array_equal(right, right) assert not left.equals(right) # with mask[1] = True, the only difference is data[1], which should # not matter for equals mask[1] = True assert left.equals(right)